简体   繁体   English

检查对象列表是否包含Java中的另一个对象

[英]Check if a list of objects contains another object in Java

Why does ts.contains(t) return false and how can I fix it? 为什么ts.contains(t)返回false ,我该如何解决? Have a look at my code, please: 看一下我的代码,请:

class MyList {
    private String x;

    public MyList (String x) {
        this .x = x;
    }

    public String toString () {
        return x;
    }   

    public static void main ( String [] args ) {
        List<MyList> ts = new ArrayList<MyList>();
        ts.add (new MyList ("one"));
        ts.add (new MyList ("two"));
        ts.add (new MyList ("three"));

        MyList t = new MyList("one");
        System.out.println ("Is t in ts? " + ts.contains(t));
    }
}

Thank you all for the help. 谢谢大家的帮助。 Both SamzSakerz and michaeak answers work correctly. SamzSakerz和michaeak答案都可以正常工作。

Just implement the equals() method: 只需实现equals()方法:

class MyList {
    private String x;

    public MyList (String x) {
        this .x = x;
    }

    @Override
    public String toString () {
        return x;
    }   


    public static void main ( String [] args ) {
        List<MyList> ts = new ArrayList<MyList>();
        ts.add (new MyList ("one"));
        ts.add (new MyList ("two"));
        ts.add (new MyList ("three"));

        MyList t = new MyList("one");
        System.out.println ("Is t in ts? " + ts.contains(t));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        MyList other = (MyList) obj;
        if (x == null) {
            if (other.x != null) {
                return false;
            }
        } else if (!x.equals(other.x)) {
            return false;
        }
        return true;
    }
}

Output Is t in ts? true 输出Is t in ts? true Is t in ts? true

The equals() Method is defined for the class Object which is the top class for every class. 为类Object定义了equals()方法,该类是每个类的顶级类。 The contains() Method contractually checks, if the requested object a is contained in the list (ie same object is contained in a list) or if an equal object b (ieaequals(b) is true) is contained in the list. contains()方法以合同方式检查所请求的对象a是否包含在列表中(即,同一对象包含在列表中)或相等的对象b(即aequals(b)为true)包含在列表中。

For List.contains(obj) the hashCode method is not required to be implemented, however, it is recommended to implement hashCode() whenever you implement equals() and make sure to depend on the same attributes in both methods. 对于List.contains(obj) ,不需要实现hashCode方法,但是,无论何时实现equals()并确保两个方法都依赖于相同的属性,建议实现hashCode()

You have to override the equals and hashCode methods. 您必须重写equalshashCode方法。

contains relies on equals , and the default implementation of equals is that its identity is compared. contains依赖于equals ,而equals的默认实现是对其身份进行比较。 Then equals only returns true if it is the very same object. 然后,如果equals是完全相同的对象,则equals仅返回true。

In order to implement the equals method, you have to decide when two objects are considered equal. 为了实现equals方法,您必须确定何时将两个对象视为相等。 In your case, I assume that if the object's only field s is equal to the other, then you want them to be considered equal. 在您的情况下,我假设如果对象的唯一字段s与另一个字段相等,那么您希望将它们视为相等。

More: 更多:

您可以使用以下命令检查列表中是否包含具有特定属性的对象

        System.out.println("Is t in ts? " + ts.stream().anyMatch(x -> x.x.equals("one")));

Like others have pointed you need to override equals and hashcode we can do this in 1 line. 就像其他人指出的那样,您需要重写equalshashcode我们可以在1行中完成此操作。

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

@Override
public boolean equals(Object obj) {
    return this == obj || obj != null && getClass() == obj.getClass() && toString().equals(obj.toString());
}

and now the output we get is 现在我们得到的输出是

Is t in ts? true

Here is the full code: 这是完整的代码:

import java.util.ArrayList;
import java.util.List;

class MyList {
    private String x;

    public MyList(String x) {
        this.x = x;
    }

    public static void main(String[] args) {
        List<MyList> ts = new ArrayList<MyList>();
        ts.add(new MyList("one"));
        ts.add(new MyList("two"));
        ts.add(new MyList("three"));

        MyList t = new MyList("one");
        System.out.println("Is t in ts? " + ts.contains(t));
    }

    @Override
    public String toString() {
        return x;
    }

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

    @Override
    public boolean equals(Object obj) {
        return this == obj || obj != null && getClass() == obj.getClass() && toString().equals(obj.toString());
    }
}

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

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