简体   繁体   中英

List contains method for object

I am trying to understand contains() along with equals and hashCode method of Object class

Below is my class 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. That the reason , why my equals method is returning true.

Any input would be helpful.

Thanks !!!

Because 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. If you instead use list1.contains(obj1); you will get true, of course, since that actual object exists in the list.

You can use containsAll(Collection<?> c); which will take a list and check if all elements in the supplied list exists within the list being invoked upon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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