【问题标题】:How to get the index of a specific item in an ArrayList?如何获取 ArrayList 中特定项目的索引?
【发布时间】:2023-03-14 05:07:01
【问题描述】:

我在Array List 中填写了一些数字,并希望在Array List 中找到一个特定数字,并在我的Array List 中获取它的位置(索引)。

任何例子都会很棒!

例如

ProClon.indexOf(spro.getId(id));

【问题讨论】:

  • 什么类型的对象?
  • 请分享您的代码,希望看到您的努力
  • 您的标签已经包含答案...
  • 对象是整数类型
  • Ifrahim:你为什么首先问这个问题?您在问题中的示例正是它是如何完成的。

标签: java object arraylist get indexof


【解决方案1】:

首先使用指定字段覆盖 equals() 方法。那么你可以使用 indexOf.(object)

class A {

    int i;

    // other fields

    public A(int i) {
       this.i = i;
    }  
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        A a = (A) o;

        return i == a.i;

    }

    @Override
    public int hashCode() {
        return i;
    }
}

List<A> list = new ArrayList<>();
list.indexOf(new A(3));

【讨论】:

    【解决方案2】:

    检查arrayList的api。 indexOf(对象 o);完全满足您的需求。 http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)

    【讨论】:

      【解决方案3】:

      只需在数组中使用方法 indexOf arrayName.indexOf(object)

      【讨论】:

        猜你喜欢
        • 2017-10-18
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 2017-01-12
        • 1970-01-01
        • 2022-11-23
        相关资源
        最近更新 更多