简体   繁体   English

List包含对象的方法

[英]List contains method for object

I am trying to understand contains() along with equals and hashCode method of Object class 我试图理解contains()以及Object类的equals和hashCode方法

Below is my class Test1 下面是我的Test1课程

public class Test1 {

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Test1)) {
            return false;
        }
        Test1 other = (Test1) obj;
        if (favoriteUID == null) {
            if (other.favoriteUID != null) {
                return false;
            }
        } else if (!favoriteUID.equals(other.favoriteUID)) {
            return false;
        }
        return true;
    }

    private String favoriteUID;

    public String getFavoriteUID() {
        return favoriteUID;
    }

    public void setFavoriteUID(String favoriteUID) {
        this.favoriteUID = favoriteUID;
    }
}

And that my main class 那是我的主要课程

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class FavoriteMain 
{

    public static void main(String[] args) 
    {

        Test1 obj1 = new Test1();
        obj1.setFavoriteUID("1");

        Test1 obj2 = new Test1();
        obj2.setFavoriteUID("1");

        List<Test1> list1 = new ArrayList<Test1>();
        list1.add(obj1);
        list1.add(obj2);

        List<Test1> list2 = new ArrayList<Test1>();
        list2.add(obj1);

        System.out.println(obj1.equals(obj2 ));
        System.out.println(list1.contains(list2));
}
}

Output is 输出是

true
false

I m buzz , why I am getting false , even my hashCode and equals method are working correctly. 我嗡嗡声,为什么我变得虚假,甚至我的hashCode和equals方法都正常工作。 That the reason , why my equals method is returning true. 这就是为什么我的equals方法返回true的原因。

Any input would be helpful. 任何输入都会有所帮助。

Thanks !!! 谢谢 !!!

Because contains(Object o); 因为contains(Object o); will look for the object in the list, for that to return true you would need to add the list itself , which would not make much sense. 将查找列表中的对象,为了返回true,您需要添加列表本身 ,这没有多大意义。 If you instead use list1.contains(obj1); 如果你改为使用list1.contains(obj1); you will get true, of course, since that actual object exists in the list. 当然,你会得到真实,因为列表中存在该实际对象。

You can use containsAll(Collection<?> c); 你可以使用containsAll(Collection<?> c); which will take a list and check if all elements in the supplied list exists within the list being invoked upon. 这将获取一个列表并检查提供的列表中的所有元素是否都存在于被调用的列表中。

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

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