在Java ArrayList中比较元素

huangapple go评论76阅读模式
英文:

Comparing elements in Java Arraylist

问题

第一个打印假,第二个打印真。

英文:
List<Integer> li= Arrays.asList(106,106,248,248,286,286,344,357,357);
  System.out.println(li.get(4) == li.get(5));
        System.out.println(li.get(0) == li.get(1));

Why first one print false and second print true

答案1

得分: 1

原始类型 int 在添加到 ArrayList 之前已经被装箱成 Integer 对象,

这解释了为什么您的比较可能会失败。等号操作符将在对象相同的情况下返回 true。您可以将相同的整数值装箱到两个不同的 Integer 对象中,因此等号操作符将返回 false。

"要在Java中比较两个Integer对象,您可以使用equals()方法。equals()方法比较两个对象的值,如果它们相等,则返回true,否则返回false。在这个例子中,equals()方法用于比较num1和num2的Integer对象。"

请参阅比较Integer对象

英文:

The primitive type int has been boxed into Integer objects prior to being added into the ArrayList

That explains why your comparisons might fail. The equality operator will result in true if the objects are the same. You could have the same integer values boxed into two different Integer objects and consequently the equal operator will result to false.

"To compare two Integer objects in Java, you can use the equals() method. The equals() method compares the value of the two objects and returns true if they are equal, or false if they are not. In this example, the equals() method is used to compare the num1 and num2 Integer objects."

See Comparing Integer Objects

huangapple
  • 本文由 发表于 2023年5月28日 15:58:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定