英文:
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."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论