java 比较 ArrayList 问题中的新整数对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2633873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare new Integer Objects in ArrayList Question
提问by ericso
I am storing Integer objects representing an index of objects I want to track. Later in my code I want to check to see if a particular object's index corresponds to one of those Integers I stored earlier. I am doing this by creating an ArrayList and creating a new Integer from the index of a for loop:
我正在存储表示要跟踪的对象索引的 Integer 对象。稍后在我的代码中,我想检查特定对象的索引是否对应于我之前存储的那些整数之一。我通过创建一个 ArrayList 并从 for 循环的索引创建一个新的整数来做到这一点:
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));
}
}
I then want to check later if the ArrayList contains a particular index:
然后我想稍后检查 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
}
}
My question is, when I create a new Integer by using new Integer(i)will I be able to compare integers using ArrayList.contains()? That is to say, when I create a new object using new Integer(i), will that be the same as the previously created Integer object if the int value used to create them are the same?
我的问题是,当我通过 using 创建一个新的 Integer 时,new Integer(i)我是否能够使用ArrayList.contains()? 也就是说,当我使用创建一个新对象时new Integer(i),如果用于创建它们的int值相同,那么它会与之前创建的Integer对象相同吗?
I hope I didn't make this too unclear. Thanks for the help!
我希望我没有把这说得太清楚。谢谢您的帮助!
回答by cletus
Yes, you can use List.contains()as that uses equals()and an Integersupports that when comparing to other Integers.
是的,与其他s相比,您可以使用List.contains()as that 使用equals()并Integer支持它Integer。
Also, because of auto-boxing you can simply write:
此外,由于自动装箱,您可以简单地编写:
List<Integer> list = new ArrayList<Integer>();
...
if (list.contains(37)) { // auto-boxed to Integer
...
}
It's worth mentioning that:
值得一提的是:
List list = new ArrayList();
list.add(new Integer(37));
if (list.contains(new Long(37)) {
...
}
will alwaysreturn falsebecause an Integeris not a Long. This trips up most people at some point.
将始终返回,false因为 anInteger不是 a Long。这在某些时候会绊倒大多数人。
Lastly, try and make your variables that are Java Collections of the interface type not the concrete type so:
最后,尝试使您的变量是接口类型的 Java 集合而不是具体类型,因此:
List<Integer> courseselectItems = new ArrayList();
not
不是
ArrayList<Integer> courseselectItems = new ArrayList();
回答by Bert F
My question is, when I create a new Integer by using new Integer(i) will I be able to compare integers using ArrayList.contains()? That is to say, when I create a new object using new Integer(i), will that be the same as the previously created Integer object if the int value used to create them are the same?
我的问题是,当我使用 new Integer(i) 创建一个新的 Integer 时,我是否能够使用 ArrayList.contains() 来比较整数?也就是说,当我使用new Integer(i)创建一个新对象时,如果用于创建它们的int值相同,那么它是否与之前创建的Integer对象相同?
The short answer is yes.
简短的回答是肯定的。
The long answer is ...
长答案是...
That is to say, when I create a new object using new Integer(i), will that be the same asthe previously created Integer object if the int value used to create them are the same?
也就是说,当我使用new Integer(i)创建一个新对象时,如果用于创建它们的int值相同,那么它是否与之前创建的Integer对象相同?
I assume you mean "... will that be the same instanceas ..."? The answer to that is no- calling newwill always create a distinct instance separate from the previous instance, even if the constructor parameters are identical.
我假设您的意思是“......这将与......相同的实例”?答案是否定的- 调用new将始终创建一个与前一个实例分开的不同实例,即使构造函数参数相同。
However, despite having separate identity, these two objects will have equivalent value, i.e. calling .equals() between them will return true.
然而,尽管具有单独的标识,这两个对象将具有等效的值,即在它们之间调用 .equals() 将返回 true。
Collection.contains()
Collection.contains()
It turns out that having separate instances of equivalent value (.equals() returns true) is okay. The .contains()method is in the Collectioninterface. The Javadoc description for .contains()says:
事实证明,具有等效值的单独实例(.equals() 返回 true)是可以的。该.contains()方法在Collection接口中。的 Javadoc 描述 .contains()说:
http://java.sun.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)
http://java.sun.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)
boolean contains(Object o)
Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).
布尔值包含(对象 o)
如果此集合包含指定的元素,则返回 true。更正式地说,当且仅当此集合包含至少一个元素 e 使得 (o==null ? e==null : o.equals(e))时才返回 true 。
Thus, it will do what you want.
因此,它会做你想做的。
Data Structure
数据结构
You should also consider whether you have the right data structure.
您还应该考虑您是否拥有正确的数据结构。
Is the list solely about containment? is the order important? Do you care about duplicates? Since a list is order, using a list can imply that your code cares about ordering. Or that you need to maintain duplicates in the data structure.
该清单仅与遏制有关吗?顺序重要吗?你关心重复吗?由于列表是顺序,因此使用列表可能意味着您的代码关心排序。或者您需要在数据结构中维护重复项。
However, if order is not important, if you don't want or won't have duplicates, and if you really only use this data structure to test whether contains a specific value, thenyou might want to consider whether you should be using a Setinstead.
但是,如果顺序不重要,如果您不想要或不会有重复项,并且您真的只使用此数据结构来测试是否包含特定值,那么您可能需要考虑是否应该使用改为设置。
回答by Binil Thomas
As cletus and DJ mentioned, your approach will work.
正如 cletus 和 DJ 所提到的,你的方法会奏效。
I don't know the context of your code, but if you don't care about the particular indices, consider the following style also:
我不知道你的代码的上下文,但如果你不关心特定的索引,也可以考虑以下样式:
List<Node> courseSelectNodes = new ArrayList<Node>();
//Find the course elements that are within a courseselect element
//and add them to the ArrayList
for(Node node : numberElementsInNodeList) {
if (node.getParentNode().getNodeName().equals("courseselect")) {
courseSelectNodes.add(node);
}
}
// Do stuff with courseSelectNodes
for(Node node : courseSelectNodes) {
//Do Stuff
}
回答by Carl Manaster
I'm putting my answer in the form of a (passing) test, as an example of how you might research this yourself. Not to discourage you from using SO - it's great - just to try to promote characterization tests.
我以(通过)测试的形式给出我的答案,作为您自己如何研究的一个例子。不要阻止您使用 SO - 这很好 - 只是为了尝试促进特性测试。
import java.util.ArrayList;
import junit.framework.TestCase;
public class ContainsTest extends TestCase {
public void testContains() throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>();
assertFalse(list.contains(new Integer(17)));
list.add(new Integer(17));
assertTrue(list.contains(new Integer(17)));
}
}
回答by Sean
Short answer is yes, you should be able to do ArrayList.contains(new Integer(14)), for example, to see if 14 is in the list. The reason is that Integer overrides the equalsmethod to compare itself correctly against other instances with the same value.
简短的回答是肯定的,ArrayList.contains(new Integer(14))例如,您应该能够查看 14 是否在列表中。原因是 Integer 覆盖了该equals方法以正确地将自身与具有相同值的其他实例进行比较。
回答by DJ.
Yes it will, because List.contains()use the equals()method of the object to be compared. And Integer.equals()does compare the integer value.
是的,它会,因为List.contains()使用equals()要比较的对象的方法。并且Integer.equals()确实比较整数值。
回答by nick
Yes, automatic boxing occurs but this results in a performance penalty. Its not clear from your example why you would want to solve the problem in this manner.
是的,会发生自动装箱,但这会导致性能下降。从您的示例中不清楚您为什么要以这种方式解决问题。
Also, because of boxing, creating the Integer class by hand is superfluous.
此外,由于拳击,手动创建 Integer 类是多余的。

