猿问

关于list集合和set集合的问题请大神指导一下

请问各位大牛list和set调用contains方法时是比较两个元素的地址,还是调用他们的equals方法呢?


public class Foo {

    int value;

    public Foo(int value) {

        this.value = value;

    }

    public boolean equals(Object obj) {

        if (obj instanceof Foo) {

            Foo foo = (Foo) obj;

            return value == foo.value;

        } else {

            return false;

        }

    }

    public static void main(String[] args) {

        //运行下面程序段:

        ArrayList list = new ArrayList();

        HashSet set = new HashSet();

        list.add(new Foo(1));

        set.add(new Foo(1));

        System.out.println(list.contains(new Foo(1)) + ","+ set.contains(new Foo(1)));

        //或者

        System.out.println(new Foo(1).equals (new Foo(1)) + ","+ set.contains(new Foo(1)));     

    }

}

我想问的就是为什么这个输出的结果是true,false


qq_遁去的一_1
浏览 461回答 3
3回答

浮云间

&nbsp; &nbsp; public boolean contains(Object o) {&nbsp; &nbsp; Iterator<E> it = iterator();&nbsp; &nbsp; if (o==null) {&nbsp; &nbsp; &nbsp; &nbsp; while (it.hasNext())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (it.next()==null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; while (it.hasNext())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (o.equals(it.next()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; return false;}这个是AbstractCollection的实现, AbstractList, AbstractSet都是以此为父类实现的.
随时随地看视频慕课网APP

相关分类

Java
我要回答