0

我对 ArrayList contains 方法的工作原理有疑问。举个例子:

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");

它返回“不包含”。

另一个例子:

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");

它返回包含。那么 contains 方法是如何工作的呢?

谢谢

4

4 回答 4

4

您正在将您的字符串添加到列表中lstStr

lstStr.add(tempStr1);

但你正在使用contains方法lst

if (lst.contains(tempStr2))

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

于 2013-09-20T15:38:32.960 回答
2

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;
    }
于 2013-09-20T15:44:17.540 回答
0

第二部分重复:ArrayList 的 contains() 方法如何评估对象?

您需要重写 equals 方法以使其按您的意愿工作。

于 2013-09-20T15:41:11.080 回答
0

在代码的第一部分:

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

bothtempStr1tempStr2引用两个不同的 2 字符串对象。在 tempStr1 引用的 String 对象被codelstStr.add(tempStr1);.so 添加到 List 之后,List 只有一个不是由tempStr1nottempStr2引用 的 String 对象。但是contains();方法对方法起作用。如果 String 对象的内容被引用,equals()lstStr.contains(temp2);返回 truetemp2与添加到的 String 对象的内容相同,List并且在找不到匹配时返回 false。这里lstStr.contains(temp2);返回 true,因为 String 对象 temp2 的内容等于添加到的 String 对象 temp1 的内容。但是List在您的代码中其中lstStr.contains(temp2);提到:

lst.contains(temp2);

在这里,您使用不同的List引用变量 ( lst) 而不是 ( lstStr)。这就是它返回 false 并执行 else 部分的原因。

在代码的第二部分setGeoCode()未定义。

于 2013-09-20T17:18:44.240 回答