【问题标题】:Very Wired thing happens when I compare two elements of the ArrayList [duplicate]当我比较 ArrayList 的两个元素时,会发生非常奇怪的事情 [重复]
【发布时间】:2016-05-04 01:43:56
【问题描述】:
public static void main(String[] args) {
    ArrayList<Integer> myList = new ArrayList<Integer>();
    myList.add(2000);
    myList.add(2000);
    myList.add(2);
    myList.add(2);

    if(myList.get(1)==myList.get(0))System.out.println("2000 equal check");
    if(myList.get(1)!=myList.get(0))System.out.println("2000 not equal check");
    if(myList.get(2)==myList.get(3))System.out.println("2 equal check");
    if(myList.get(2)!=myList.get(3))System.out.println("2 not equal check");
}

我的代码如上所示。结果如下所示。

2000 不等于校验

2等号检查

The results show me very wired things..

我真的很困惑......如果有人可以帮助我,我很感激。

【问题讨论】:

  • 请阅读how to ask good questions 并尝试编辑您的问题。有了高质量的问题,您将更快地收到更好的答案。谢谢!
  • 我注意到你的问题仍然是“开放的”——因为你没有接受答案。请查看并决定是否要accept 回答。或者让我知道我是否可以做些什么来增强我的输入以使其被接受。接受有助于未来的读者确定问题是否已解决,并对花时间回答你的人表示感谢。谢谢!

标签: java arraylist


【解决方案1】:

您不得使用 == 比较引用类型(任何对象)。始终使用 equals()。

如果两个 Object 引用指向内存中的相同对象,

== 返回 true。

鉴于此,问题在于 Integer 对象是如何存在的:

在处理您的源代码时,编译器会为您做不同的事情 添加(2000)和添加(2):

对于 -127 和 128 之间的值...编译器实际上不会创建一个新的 Integer 对象,而是做一些“智能”缓存...所以 add(2) 总是添加 SAME 对象实例。

因此,使用 == 的引用相等性检查返回 true。对于add(2000),每次返回一个新对象;因此 == 返回 false。

【讨论】:

  • new Integer(2) == new Integer(2) 将永远为真”说什么? [不,它没有,那个表达式总是返回 FALSE] 你最好尝试一下,然后重写你的答案。
  • 注意:new Integer(2)不是当 OP 执行 myList.add(2); 时会发生什么
  • 你是对的;昨天写的时候好像睡着了。固定的;谢谢!
【解决方案2】:

您正在使用Integer 对象,因此,您应该使用.equals()

if(myList.get(1).equals(myList.get(0)))
     System.out.println("2000 equal check");
if(!myList.get(1).equals(myList.get(0)))
     System.out.println("2000 not equal check");
// works because of: see link in the comments to your question
if(myList.get(2)==myList.get(3))System.out.println("2 equal check");
if(myList.get(2)!=myList.get(3))System.out.println("2 not equal check");

The link from the comment section of your question.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多