开发者

read ArrayList elements

Why it print the wrong output?

ArrayList<String> loc = new ArrayList<String>();

This arraylist stored the value of:

[topLeft, topLeft, topLeft, bottomLeft, topLeft, bottomLeft, topLeft, topLeft, Left, topLeft]

the firs index 0 is = topLeft

if(loc.get(1)=="topLeft")
   System.out.println("same")

else {
   System.out.println("not same")
}开发者_StackOverflow中文版

This program print the wrong output not same instead of same


Use the equals(Object) method, not the == operator, for example loc.equals("topLeft")

The == operator returns true if two references point to the same Object in memory. The equals(Object o) method checks whether the two objects are equivalent, so will return true if two Strings contain only the same characters in the same order.


String comparison is done by calling str1.equals(str2) rather than using ==.

  • equals(..) compares the strings' contents
  • == compares the references, and they are not the same.

There is a little more to know, however. String objects that are initialized as literals, i.e.

String str = "someString"

instead of via construction (String str = new String("some")) are all the same object. For them == would work.

And finally, for any String, calling intern() returns a String that is the same object as all other strings with the same content. (read intern()'s documentation for more info)

But the best practice here is to use equals(), while being careful if the object you are calling it on (the first string) is not null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜