Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Help with Interview Code I had

Hey guys, I attended a Java Interview yesterday and they gave me a test. One of the questions asked me to implement a Java method that takes two int[] arrays and returns only the unique numbers. I failed this question, because I couldnt think of anything in the exact moment. Now when I am home I came with a solution that I cannot really finish.

My code is below:

public class Main {

public static void arraySort(int[] arrayOne, int[] arrayTwo) {

    Set<int[]> set = new HashSet<int[]>();
    set.add(arrayOne);
    set.add(arrayTwo);

    // how do I print the Set here?
}

public static void main(String[] args) {

    int[] arrayOne = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int[] arrayTwo = {1, 2, 10, 3, 4, 5, 6, 7, 8, 9, 11};

    arraySort(arrayOne, arrayTwo);


}

I have tried a lot of implementations, but everything returned [[I@6d6f6e28, [I@7f31245a] - the object reference.

Can anyone help me here?

I am kinda stuck, cannot find an answer on StackOverflow as well...

2 Answers

Deividas Strioga
Deividas Strioga
12,851 Points

You cannot add arrays to sets this way. I tried this code with for each loop, it worked:

package sample;

import java.util.HashSet;
import java.util.Set;

public class Test {

    public static void arraySort(int[] arrayOne, int[] arrayTwo) {
        Set<Integer> set = new HashSet<>();
        for (int i : arrayOne){
            set.add(i);
        }
        for (int i : arrayTwo){
            set.add(i);
        }
        System.out.println(set);
    }

    public static void main(String[] args) {
        int[] arrayOne = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] arrayTwo = {1, 2, 10, 3, 4, 5, 6, 7, 8, 9, 11};
        arraySort(arrayOne, arrayTwo);
    }
}

And it prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

How much time did you have for this task?

Thanks! I see where I was wrong. I had 7 minutes to complete this exercise, before their system flipped my page. Never occurred to me that I have to loop over the 2 arrays before I add them into the Set...