Java 检查 ArrayList 是否包含给定对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16273310/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:07:38  来源:igfitidea点击:

Check if an ArrayList contains a given object

javalistarraylist

提问by Saulius S

Assuming I have class like this:

假设我有这样的课程:

class A {
  int elementA;
  int elementB
}

I also have an ArrayListlike this: ArrayList<A> listObj.

我也有ArrayList这样的:ArrayList<A> listObj

How can I check if that list contains an object using only some of the properties of A? E.g. considering only elementAfor finding if object newA{elementA}is already in the list?

如何仅使用 的某些属性来检查该列表是否包含对象A?例如,仅考虑elementA查找对象newA{elementA}是否已在列表中?

For object AI have defined an equalsmethod, where I consider only the elementA, however this is not enough.

对于对象,A我定义了一个equals方法,我只考虑了elementA,但这还不够。

回答by Hariharan

The hashCode()and equals()of arrays are a bit broken when it comes to this (it is a long different discussion why).

涉及到这一点时,数组的hashCode()andequals()有点坏(这是一个很长的不同讨论为什么)。

A possible work around is to use ArrayList<ArrayList<String>>instead of ArrayList<String[]>, the equals() method for ArrayList will be as you expect it to.

一种可能的解决方法是使用ArrayList 的 equals() 方法ArrayList<ArrayList<String>>代替ArrayList<String[]>,这将如您所愿。

For example:

例如:

   ArrayList<String> l1 = new ArrayList<>();
    ArrayList<String> l2 = new ArrayList<>();
    l1.add("asdf");
    l2.add("asdf");
    ArrayList<ArrayList<String>> coll = new ArrayList<>();
    coll.add(l1);
    System.out.println(coll.contains(l2));

Will yield true, as expected

正如预期的那样,将产生 true

Also refer below link

另请参阅以下链接

Most efficient way to see if an ArrayList contains an object in Java

在 Java 中查看 ArrayList 是否包含对象的最有效方法

回答by NINCOMPOOP

List#contains()method uses the equals()method to evaluate if two objects are the same. So, you need to override equals()in your Class Aand also override the hashCode().

List#contains()方法使用该equals()方法来评估两个对象是否相同。因此,您需要equals()在您的类中A覆盖并覆盖hashCode().

@Override
public boolean equals(Object object)
{
    boolean isEqual= false;

    if (object != null && object instanceof A)
    {
        isEqual = (this.elementA == ((A) object).elementA);
    }

    return isEqual;
}

@Override
public int hashCode() {
    return this.elementA;
}

回答by Vincent van der Weele

I wouldn't override equalsfor this. Even though {1, 1}and {1, 2}cannot both occur in your list, the two objects are notequal.

我不会equals为此覆盖。尽管{1, 1}{1, 2}不能同时出现在您的列表中,但这两个对象并不相等。

I would use a Mapinstead:

我会用 aMap代替:

Map<Integer, A> map = new HashMap<>();
A a1 = new A(1, 1);
A a2 = new A(1, 2);

map.put(a1.elementA, a1);

// test if key is contained
boolean contains = map.containsKey(a2.elementA);

// overwrite a1 with a2
map.put(a2.elementA, a2);

回答by NilsH

You could adapt your equalsto accomodate for your needs, but you could also use one of the powerful collection libraries that already exists, like commons-collections, Guavaor lambdaj. They all have iteration and predicate constructs that allow you to "explore" your collections based on some predicate.

您可以equals根据自己的需要进行调整,但您也可以使用已经存在的强大集合库之一,例如commons-collectionsGuavalambdaj。它们都有迭代和谓词构造,允许您基于某些谓词“探索”您的集合。

Example with Commons Collections:

Commons 集合的示例:

boolean contains = CollectionUtils.exists(myArrayList, new Predicate<A>() {
    public boolean evaluate(A theA) {
        // Do the comparison
    }
});

回答by NilsH

All the above solution will suits your question. What i like to suggest you here is !!! When ever you use collection, always have your variable datatype to its super class. which will help you to make more manipulation and convert to any of its sub-class.

以上所有解决方案都适合您的问题。我想在这里建议你的是!!!当您使用集合时,始终将您的变量数据类型设置为它的超类。这将帮助您进行更多操作并转换为它的任何子类。

Ex:
List<String> myList = new ArrayList<String>();

The advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This is will be difficult to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.

List 的实现可以更改(例如更改为 LinkedList),而不影响其余代码的优点。使用 ArrayList 很难做到这一点,不仅因为您需要在任何地方将 ArrayList 更改为 LinkedList,还因为您可能使用了 ArrayList 特定方法。

回答by Aman Goyal

For comparing the object value in arrayList. Follow this Link. How to compare Objects attributes in an ArrayList?

用于比较arrayList. 按照这个链接。 如何比较 ArrayList 中的对象属性?

I hope this solution will help you. Thanks

我希望这个解决方案能帮助你。谢谢

回答by Mpendulo

List<Upload> mUploadPost = new ArrayList<Upload>();
Upload upload = new Upload();
upload.addName("Mpendulo");
upload.addLastName("Mtshali");
if(!mUploadPost.contains(upload)){
    mUploadPost.add(upload);
}