【问题标题】:How ArrayList contains method work? [closed]ArrayList 包含方法如何工作? [关闭]
【发布时间】:2013-09-20 15:35:35
【问题描述】:

我对 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 方法是如何工作的呢?

谢谢

【问题讨论】:

  • 如果你修复你的例子调用lstStr.contains,它确实工作。 (没有名为lst 的变量。)我建议你删除这个问题,然后编辑它,然后当你有一个真正的 简短但完整的程序来证明问题时取消删除它。
  • 第二部分是重复的:stackoverflow.com/questions/2642589/…

标签: java object arraylist equals primitive


【解决方案1】:

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

lstStr.add(tempStr1);

但您在lst 上使用contains 方法

if (lst.contains(tempStr2))

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

【讨论】:

    【解决方案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;
        }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • String 是 Java 库类并且实现了正确的 equals 方法...
      【解决方案4】:

      在第一段代码中:

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

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

      lst.contains(temp2);
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-29
        • 2014-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多