Reputation: 429
I am trying to compare the first element in an arraylist to the rest of the elements.
Then comparing the second element of the arraylist to the rest of the elements and so on until
the end of the arraylist.
The code is as below:
ArrayList<String> a = new ArrayList<String>();
a.add("G1");
a.add("G2");
a.add("G3");
a.add("G1");
System.out.println(a.size());
for(int i = 0; i<a.size(); i++){
for(int j = 0; j<a.size(); j++){
if(a.get(i) == a.get(j))
System.out.println("Element: " + a.get(i)+ " at " + i + " and " + "Element: "+ a.get(j)+ " at " + j);
}
}
Upvotes: 0
Views: 308
Reputation: 1547
Use this code, instead of yours.
for(int i = 0; i<a.size()-1; i++){
for(int j = i+1; j<a.size(); j++){
if(a.get(i).equals(a.get(j)))
System.out.println("Element: " + a.get(i)+ " at " + i + " and " + "Element: "+ a.get(j)+ " at " + j);
}
Hope that helps.. :)
Upvotes: 1
Reputation: 4715
Use
if((a.get(i)).equals(a.get(j)))
instead of
if(a.get(i) == a.get(j))
Morover start your initialization of j = i+1
You have already checked these previous string so no need to start it again.
EDIT
You have to limit your outer loop to i<a.size()-1
so that it wont check very last element with itself.
I hope this helps. if you need anymore help just ask.
Upvotes: 0
Reputation: 2416
In your case, since you're using Strings, instead of using ==, which is referential equality, as in are the memory addresses the same, you want to use .equals()
which will compare the two strings by their actual values.
As for your for-loop, you can make it slightly more efficient by doing this.
for (int i = 0; i < a.size()-1; i++)
{
for (int j = i+1; j < a.size(); j++)
{
if(a.get(i).equals(a.get(j)))
{
System.out.println("Element: " + a.get(i)+ " at " + i + " and " + "Element: "+ a.get(j)+ " at " + j);
}
}
}
Since there are times when you already compare a[i] with a[j], the result will be the same if you do a[j] equals a[i], so you can just skip over them. This also saves you from checking a[i] equals a[j] when j and i are the same.
Upvotes: 0
Reputation: 38511
==
is reference equality (e.g do these two objects point to the same location in memory). For object equality, use .equals()
instead.
Upvotes: 1