【问题标题】:Get index of ArrayList of various data types获取各种数据类型的ArrayList的索引
【发布时间】:2013-12-10 12:01:11
【问题描述】:

这里是java新手。我有一个 ArrayList,其中包含包含字符串和整数的对象。对象的构造函数的结构类似于MyClass(String, String, int, int, String)。我想在构造函数中使用 String 的第一个实例来查找 ArrayList 元素的索引,但我不知道如何去做。我尝试使用indexOf(),但未能成功找到特定元素的索引。如果有人能指出我正确的方向,我将不胜感激。干杯

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

    您必须覆盖 MyClass 中的等于。 根据您想要实现的目标,您的 equals 方法如下所示:

    public boolean equals(Object o) {
       if (o== null) return false;
       if (!(o instanceof MyClass)) return false;
       MyClass other = (MyClass) o;
       if (other.firstString != null && this.firstString != null 
        && this.firstString.equals(other.firstString) return true;
       return false;
    }
    

    编辑:您也应该覆盖 hashCode。覆盖 hashCode 时,您应该考虑覆盖 equals 时考虑的对象。因此,如果您基于属性 firstString 测试两个 MyClass 对象是否相等,则应在 hashCode

    中包含 firstString
    public int hashCode() {
        if (firstString == null) return 31;
        return firstString.hashCode();
    
    }
    

    编辑2: 调用 indexOf 时 ArrayList 的作用基本上是这样的: 'for (Entry e = header.next; e != header; e = e.next) { 如果(o.equals(e.element)) 回报指数; 索引++; }'

    因此,每次调用 indexOf() 时,ArrayList 都会在对象上调用 equals 方法。 因此,假设您有一个如下所示的列表:

    MyClass m1 = new MyClass("this is some random string", other params);
    MyClass m2 = new MyClass("this is my target string", other params);
    MyClass m3 = new MyClass("this is irrelevant", other params);
    
    list.add(m1);
    list.add(m2);
    list.add(m3);
    

    现在,您想知道包含“这是我的目标字符串”的 MyClass 对象的索引。 所以你调用 indexOf:

    list.indexOf(new MyClass("this is my target string"), other params);
    

    并且,根据您的 equals 实现,它将返回 1。

    【讨论】:

    • 我正在看教程,并试图理清如何将其应用于获取arraylist中特定元素的索引。
    • 因此 equals 将 this 与 other 进行比较并返回 true 或 false。正确的?而hashcode使用一个素数来判断结果是否等于1?我想我还没有真正理解它。
    • indexOf 在集合中查找对象时调用 equals 方法。如果您不覆盖 equals,则将通过比较对对象的引用来测试对象是否相等。换句话说,只有当两个对象是相同的对象时,它们才会被认为是相等的。
    • HashCode 为您的对象分配一个唯一值,并在对象用作集合中的键(例如映射)时调用。在计算哈希码时通常使用素数。
    • 我想我对equals和hashCode有了初步的了解,但我仍然不明白这如何引导我找到包含this.firstString的arraylist元素的索引。我错过了什么?我已经问过我的导师,并被告知要谷歌它。非常感谢任何帮助。
    【解决方案2】:

    你必须看看如何在你的类中重写equalshashcode 方法。这是Collection的api用来执行这种操作的。

    【讨论】:

      【解决方案3】:

      如果你可以避免的话,你不认为你真的应该首先在列表中存储不同的类型吗?你真的有一个具有不同类型属性的对象列表吗?

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 2019-07-14
        • 2012-10-19
        • 2011-11-16
        • 1970-01-01
        • 2010-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多