ZAX
ZAX

Reputation: 1006

Printing Common Values of Two Arrays

I am working on a java project and need to print common values between two arrays.

I have printed both arrays in their sorted order before hand and they both look good (containing all values they should). However, when I follow the simplest of algorithms (see below) I do not find all the common values even though I can manually see in the print out of the two arrays without comparison that there should be more values printed after executing the below:

        for(int i=0; i<fibList.size(); i++)
        {
            for(int j=0; j<primeList.size(); j++)
            {
                if(fibList.get(i) == primeList.get(j))
                {
                    System.out.print(" " + fibList.get(i));
                    break;
                }
            }
        }

Please let me know what you think. Hopefully this is just a simple error.

Upvotes: 3

Views: 1419

Answers (3)

Juvanis
Juvanis

Reputation: 25950

if(fibList.get(i).equals(primeList.get(j))) could be used.

Upvotes: 4

jlordo
jlordo

Reputation: 37843

List<Integer> result = new ArrayList<Integer>(fibList);
result.retainAll(primeList);
for (Integer i : result) {
    System.out.println(i);
}

Upvotes: 4

sampson-chen
sampson-chen

Reputation: 47367

Most likely you want to:

Change:

if(fibList.get(i) == primeList.get(j))

To:

if(fibList.get(i).equals(primeList.get(j)))

Upvotes: 4

Related Questions