读取ArrayList元素
为什么它打印出错误的输出?
ArrayList<String> loc = new ArrayList<String>();
该数组列表存储的值是:
[topLeft, topLeft, topLeft, bottomLeft, topLeft, bottomLeft, topLeft, topLeft, Left, topLeft]
第一个索引 0 = topLeft
if(loc.get(1)=="topLeft")
System.out.println("same")
else {
System.out.println("not same")
}
该程序打印错误的输出 not same
而不是 same
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")
}
This program print the wrong output not same
instead of same
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
equals(Object)
方法,而不是==
运算符,例如loc.equals("topLeft")
=如果两个引用指向内存中的同一个对象,=
运算符将返回 true。 equals(Object o) 方法检查两个对象是否相等,因此如果两个字符串仅包含相同顺序的相同字符,则返回 true。Use the
equals(Object)
method, not the==
operator, for exampleloc.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.字符串比较是通过调用
str1.equals(str2)
而不是使用==
来完成的。equals(..)
比较字符串的内容==
比较引用,它们不相同。然而,还有一些事情需要了解。以文字形式初始化的 String 对象,即
不是通过构造 (String str = new String("some")) 初始化的对象都是同一个对象。对于他们来说
==
会起作用。最后,对于任何
String
,调用intern()
返回一个String
,它与具有相同内容的所有其他字符串是同一对象。 (请阅读intern()
的文档以获取更多信息)但是这里的最佳实践是使用
equals()
,同时要小心您调用它的对象 (第一个字符串)不为null
。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.instead of via construction (
String str = new String("some")
) are all the same object. For them==
would work.And finally, for any
String
, callingintern()
returns aString
that is the same object as all other strings with the same content. (readintern()
'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 notnull
.