0

I am freaked out about the following code and surprised that it didn't work. Here I want to compare two ArrayLists the way I want as in below. So I can't get match for "Green" just because it is added to the ww list with a space contained " Green" even I used trim() but still doesn't work. Thanks you very much for your expertise to help me with this strange error.

ArrayList<String> ww = new ArrayList();
ArrayList<String> mm = new ArrayList();
ww.add("Orange");
ww.add(" Green".trim());
mm.add("Orange");
mm.add("Green");

for ( String x:ww){
        for ( y:mm){
            if (x==y){
                System.out.println(x);
            }
        }
    }

After running:

Orange
jesy2013
  • 319
  • 2
  • 12

1 Answers1

2

You cannot compare two strings using == for value equality. == is only for reference equality. Revise your if-condition to be:

if(x.equals(y))

Specifically, while "Orange" exists in the constant pool (same reference for both cases of it being used), two instances of "Green" exist--one in the constant pool. and one returned by String#trim().

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • thanks for the answer. but can you please tell me why it works for Orange but not for Green? – jesy2013 Aug 16 '14 at 20:13
  • @jesy2013: Because the result of `" Green".trim()` isn't a reference to the same string as `"Green"`... whereas interning means that both `"Orange"` occurrences refer to the same string. – Jon Skeet Aug 16 '14 at 20:18
  • 2
    @jesy2013 If you assing a string using `"Orange"` the JVM will cache it internally so it doesn't has to create an new instance if you assign another string with `"Orange"`. This means both string variables reference to the same object. If you call `" Green".trim()` a completely new instance of a string containing `"Green"` will be created and assigned to your variable. So the list `ww` contains a string with `"Green"` that is not the same object as in the list `mm` even if both strings contain the same "data". – Tom Aug 16 '14 at 20:18