ArrayList如何包含方法工作?

时间:2013-09-20 15:35:36

标签: java object arraylist equals primitive

我怀疑ArrayList如何包含方法。我们来举个例子:

List<String> lstStr = new ArrayList<String>();
String tempStr1 = new String("1");
String tempStr2 = new String("1");

lstStr.add(tempStr1);

if (lst.contains(tempStr2))
    System.out.println("contains");
else
    System.out.println("not contains");

它返回'not contains'。

另一个例子:

List<LinkProfileGeo> lst = new ArrayList<LinkProfileGeo>();
LinkProfileGeo temp1 = new LinkProfileGeo();
temp1.setGeoCode("1");
LinkProfileGeo temp2 = new LinkProfileGeo();
temp2.setGeoCode("1");

lst.add(temp1);

if (lst.contains(temp2))
    System.out.println("contains");
else
   System.out.println("not contains");

它返回包含。那么包含方法的工作原理是什么?

由于

4 个答案:

答案 0 :(得分:4)

您要将字符串添加到列表lstStr

lstStr.add(tempStr1);

但您在contains

上使用lst方法
if (lst.contains(tempStr2))

您对测试的想法是正确的,因为contains在内部使用equals来查找元素,因此如果使用equals匹配字符串,那么它应该返回true。但似乎你使用了两个不同的列表,一个用于添加,另一个用于检查包含。

答案 1 :(得分:1)

如果您有兴趣,请参阅ArrayList的相关源代码。正如@ user2777005所说,你的代码中有一个拼写错误。您应该使用lstStr.contains(),而不是lst.contains()

     public int indexOf(Object o) {
        if (o==null) {
            for (int i=0; i<a.length; i++)
                if (a[i]==null)
                    return i;
        } else {
            for (int i=0; i<a.length; i++)
                if (o.equals(a[i]))
                    return i;
        }
        return -1;
    }

    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

答案 2 :(得分:0)

第二部分是:How does a ArrayList's contains() method evaluate objects?

的副本

你需要覆盖equals方法,使其按你的意愿工作。

答案 3 :(得分:0)

代码的第一部分:

String tempStr1 = new String("1");
String tempStr2 = new String("1");

tempStr1tempStr2都引用了两个不同的2字符串对象。之后,由codelstStr.add(tempStr1);添加了由tempStr1引用的String对象。所以List只有一个由tempStr1而不是tempStr2引用的String对象。但是 contains();方法的equals()方法工作。如果lstStr.contains(temp2);引用的String对象的内容与String对象的内容相同,则temp2返回true添加到List并在匹配未找到时返回false。其中lstStr.contains(temp2);返回true,因为String对象temp2的内容等于添加到List的String对象temp1的内容。但是您的代码是lstStr.contains(temp2);,它被提及为:

lst.contains(temp2);

这里您使用的是不同的List引用变量(lst)而不是(lstStr)。这就是为什么它返回false并执行其他部分。

代码setGeoCode()的第二部分中的

未定义。