我正在存储代表我要跟踪的对象索引的整数对象。稍后在我的代码中,我想检查特定对象的索引是否对应于我之前存储的那些整数之一。我通过创建一个 ArrayList 并从 for 循环的索引创建一个新的 Integer 来做到这一点:
ArrayList<Integer> courseselectItems = new ArrayList();
//Find the course elements that are within a courseselect element and add their indicies to the ArrayList
for(int i=0; i<numberElementsInNodeList; i++) {
if (nodeList.item(i).getParentNode().getNodeName().equals("courseselect")) {
courseselectItems.add(new Integer(i));
}
}
然后我想稍后检查 ArrayList 是否包含特定索引:
//Cycle through the namedNodeMap array to find each of the course codes
for(int i=0; i<numberElementsInNodeList; i++) {
if(!courseselectItems.contains(new Integer(i))) {
//Do Stuff
}
}
我的问题是,当我使用 new Integer(i)
创建一个新的 Integer 时,我是否能够使用 ArrayList.contains()
比较整数?也就是说,当我使用new Integer(i)
创建一个新对象时,如果创建它们的int值相同,那么它是否与之前创建的Integer对象相同?
我希望我没有说得太不清楚。感谢您的帮助!
最佳答案
是的,您可以使用 List.contains()
,因为它使用 equals()
并且 Integer
在与其他 比较时支持它code>整数
。
此外,由于自动装箱,您可以简单地写:
List<Integer> list = new ArrayList<Integer>();
...
if (list.contains(37)) { // auto-boxed to Integer
...
}
值得一提的是:
List list = new ArrayList();
list.add(new Integer(37));
if (list.contains(new Long(37)) {
...
}
将总是返回false
,因为Integer
不是Long
。这在某些时候会绊倒大多数人。
最后,尝试使您的变量成为接口(interface)类型的 Java 集合而不是具体类型:
List<Integer> courseselectItems = new ArrayList();
不是
ArrayList<Integer> courseselectItems = new ArrayList();
关于java - 比较 ArrayList 问题中的新整数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2633873/