开发者

read ArrayList elements

开发者 https://www.devze.com 2022-12-24 05:11 出处:网络
Why it print the wrong output? ArrayList<String> loc = new ArrayList<String>(); This arraylist stored the value of:

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

精彩评论

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