比较 ArrayList 中新的整数对象问题

发布于 2024-08-28 23:24:16 字数 984 浏览 4 评论 0原文

我正在存储表示我要跟踪的对象索引的整数对象。稍后在我的代码中,我想检查特定对象的索引是否对应于我之前存储的那些整数之一。我通过创建一个 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
    }
}

我的问题是,当我使用 创建一个新的 Integer 时new Integer(i) 我可以使用 ArrayList.contains() 比较整数吗?也就是说,当我使用new Integer(i)创建一个新对象时,如果创建它们时使用的int值相同,那么它会与之前创建的Integer对象相同吗?

我希望我没有让这件事变得太不清楚。感谢您的帮助!

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:

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:

//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?

I hope I didn't make this too unclear. Thanks for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

秋心╮凉 2024-09-04 23:24:16

是的,您可以使用 List.contains(),因为它使用 equals(),并且在与其他 Integer 进行比较时,Integer 支持这一点

另外,由于自动装箱,您可以简单地编写:

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不是>长。这在某些时候会让大多数人绊倒。

最后,尝试使变量成为接口类型的 Java 集合而不是具体类型,这样:

List<Integer> courseselectItems = new ArrayList();

不是

ArrayList<Integer> courseselectItems = new ArrayList();

Yes, you can use List.contains() as that uses equals() and an Integer supports that when comparing to other Integers.

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 always return false because an Integer is not a Long. This trips up most people at some point.

Lastly, try and make your variables that are Java Collections of the interface type not the concrete type so:

List<Integer> courseselectItems = new ArrayList();

not

ArrayList<Integer> courseselectItems = new ArrayList();
两相知 2024-09-04 23:24:16

我的问题是,当我使用 new Integer(i) 创建新的 Integer 时,我可以使用 ArrayList.contains() 比较整数吗?也就是说,当我使用new Integer(i)创建一个新对象时,如果创建它们时使用的int值相同,那么它会和之前创建的Integer对象一样吗?

简短的回答是肯定的。

长答案是......

也就是说,当我使用new Integer(i)创建一个新对象时,如果创建它们的int值相同,它会与之前创建的Integer对象相同

我假设您的意思是“...这将是与...相同的实例”吗?答案是 - 调用new将始终创建一个与前一个实例分开的不同实例,即使构造函数参数相同。

然而,尽管有单独的身份,这两个对象将具有等值,即在它们之间调用.equals()将返回true。

Collection.contains()

事实证明,拥有相同值的单独实例(.equals() 返回 true)是可以的。 .contains() 方法位于 Collection 接口中。 .contains() 的 Javadoc 描述如下:

http://java.sun.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)

布尔包含(对象o)

<块引用>

如果该集合返回 true
包含指定的元素。更多的
形式上,返回 true 当且仅当
该集合至少包含一个
元素 e 使得 (o==null ? e==null
o.equals(e))

因此,它会做你想做的事。

数据结构

您还应该考虑是否拥有正确的数据结构。

该清单仅与遏制有关吗?顺序重要吗?您关心重复项吗?由于列表是有序的,因此使用列表可能意味着您的代码关心顺序。或者您需要在数据结构中维护重复项。

但是,如果顺序不重要,如果您不希望或不会有重复项,并且您确实只使用此数据结构来测试是否包含特定值,那么您可能想要考虑是否应该使用 Set反而。

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?

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 as the previously created Integer object if the int value used to create them are the same?

I assume you mean "... will that be the same instance as ..."? The answer to that is no - calling new will always create a distinct instance separate from the previous instance, even if the constructor parameters are identical.

However, despite having separate identity, these two objects will have equivalent value, i.e. calling .equals() between them will return true.

Collection.contains()

It turns out that having separate instances of equivalent value (.equals() returns true) is okay. The .contains() method is in the Collection interface. The Javadoc description for .contains() says:

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)).

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, then you might want to consider whether you should be using a Set instead.

看海 2024-09-04 23:24:16

简短的回答是肯定的,例如,您应该能够执行 ArrayList.contains(new Integer(14)) 来查看列表中是否有 14。原因是 Integer 重写了 equals 方法,以便将自身与具有相同值的其他实例进行正确比较。

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 equals method to compare itself correctly against other instances with the same value.

雨轻弹 2024-09-04 23:24:16

是的,会的,因为 List.contains() 使用要比较对象的 equals() 方法。 Integer.equals() 确实比较整数值。

Yes it will, because List.contains() use the equals() method of the object to be compared. And Integer.equals() does compare the integer value.

把昨日还给我 2024-09-04 23:24:16

正如 cletus 和 DJ 提到的,你的方法会起作用。

我不知道你的代码的上下文,但如果你不关心特定的索引,也可以考虑以下样式:

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
}

As cletus and DJ mentioned, your approach will work.

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
}
天气好吗我好吗 2024-09-04 23:24:16

我将以(通过)测试的形式给出我的答案,作为您如何自己研究这个问题的示例。并不是阻止您使用 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)));
    }
}

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.

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)));
    }
}
软糖 2024-09-04 23:24:16

是的,会发生自动装箱,但这会导致性能损失。从您的示例中不清楚您为什么要以这种方式解决问题。

另外,由于拳击,手动创建 Integer 类是多余的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文