harsh8888
harsh8888

Reputation: 477

Comparing List elements in java

I have 2 Lists token and chords. They are populated alright. But when I try to compare the 2, they always yield a false value despite of printing identical string content when printed separately in a loop. Any ideas/workarounds?

System.out.println(token.get(i).toString().equals(chords.get(j).toString()));

Both are declared as List and initialized as ArrayList();

Both contain String objects.

while (i < tokenLength) {
    System.out.println("");
    int j = 0;
    while (j < numberOfChords) {
        System.out.println(token.get(i).toString() + " compares "
                + chords.get(j).toString());
        System.out.println(token.get(i).toString()
                .equals(chords.get(j).toString()));
        if (token.get(i).toString() == chords.get(j).toString()
                && token.get(i).toString().length() <= maxLengthOfChord) {

            foundChord.add(token.get(i));
        }
        j++;
    }
    i++;
}

gives the following output : enter image description here

I also tried this

System.out.println(token.get(i).toString().equals(chords.get(j).toString()));

It always yields a false returning the same result as shown in the screenshot

Upvotes: 1

Views: 3854

Answers (5)

Tony Arra
Tony Arra

Reputation: 11099

I'm not sure what exactly the problem is with your current code, but I did you the favor of simplifying it a bit...

for (String t : token) {
  for (String c : chords) {
    System.out.println(t + " compares " + c);
    System.out.println(t.equals(c));
    if (t.equals(c)) {
      foundChord.add(t);
    }
  }
}

If I'm understanding it correctly, that you should do what your current code is trying to achieve, and it should work without errors.

Upvotes: 1

emd
emd

Reputation: 750

This will compare references not values.

token.get(i).toString() == chords.get(j).toString()

You have to do:

token.get(i).toString().equals(chords.get(j).toString())

Upvotes: 1

Perception
Perception

Reputation: 80593

You did everything right up to this point:

if (token.get(i).toString() == chords.get(j).toString()

You need to use the equals method, not ==

Upvotes: 2

forty-two
forty-two

Reputation: 12817

Cannot say why it prints false, but this is definitively wrong:

    if (token.get(i).toString() == chords.get(j).toString()

Change that line to

    if (token.get(i).trim().equals(chords.get(j).trim())

Equality (equals()) is not the same as identity (==).

Upvotes: 1

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

toString() will by default print the hashcode of the object. This hashcode is unique for all the objects and hence it never matches with hashcode of other objects and the result is false when you compare them(even if the objects are similar). You need to override the toString() method to get expected result. May be you can return values of instance variables from toString method

Upvotes: 0

Related Questions