简体   繁体   English

检查ArrayList <>是否包含一个对象不起作用

[英]Checking if ArrayList<> cointains a object dont work

My app downloading a Events from sqldatabase and add it to ArrayList<>. 我的应用程序从sqldatabase下载事件,并将其添加到ArrayList <>。 It do aduplicate so I wrote: 它确实重复,所以我写道:

public static ArrayList<Events> list = new ArrayList<Events>();

  static void addevhlp(Events e){

        if (list.contains(e)){
         Log.d("","it cointains")
        }
        else {
            list.add(e);
        }

    }

But it never say me the list cointans element. 但是,它从来没有说过列表上的cotantans元素。 What I'm doing wrong? 我做错了什么?

you have to override equals in Events , and define when two events are equals. 您必须在Events override equals ,并定义两个事件何时相等。 The default implementation checks for equal object's reference. 默认实现检查相等对象的引用。 For instance, if your Events class has an int id field 例如,如果您的Events类具有一个int id字段

@Override
public boolean equals(Object o) {
    if (!(o instanceof Events)) {
         return false;
    }
    Events event = (Events) o;
    return id == event.id;
}

You should overrides equals and hashCode in your Events object. 您应该在事件对象中覆盖equalshashCode
See : Best implementation for hashCode method for detail about hashCode 有关hashCode的详细信息,请参见: hashCode方法的最佳实现

According to the documentation about ArrayList.contains : 根据有关ArrayList.contains文档

Returns true if this list contains the specified element. 如果此列表包含指定的元素,则返回true。 More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). 更正式地讲,当且仅当此列表包含至少一个元素(e == null?e == null:o.equals(e))时,返回true。

So, contains uses the equals implementation of your Events class to check if it holds the object. 因此, contains使用您的Events类的equals实现检查其是否包含对象。

if (list.contains(e))

If the events e has the same Reference than the one you have in the ArrayList the contains will work. 如果事件e的引用与您在ArrayList中的引用具有相同的引用,则包含将起作用。 but If you want to check if the value is the same, but with a different Reference, you have to check if the properties of your events are exists or equals. 但是,如果要检查值是否相同,但引用不同,则必须检查事件的属性是否存在或相等。

or you can simply use LINQ with List instead of ArrayList C# how to determine, whether ArrayList contains object with certain attribute 或者您可以简单地使用带有列表的LINQ而不是ArrayList C#如何确定ArrayList是否包含具有特定属性的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM