如何获取 ArrayList 中特定项目的索引?
How to get the index of a specific item in an ArrayList?
我在 Array List
中填入了一些数字,并希望找到 Array List
中的特定数字并获取其在我的 Array List
中的位置(索引)。
任何例子都很好!
例如
ProClon.indexOf(spro.getId(id));
检查arrayList的api。 indexOf(对象o);做你需要的。
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
首先用指定字段覆盖 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));
只需在数组中使用方法 indexOf
arrayName.indexOf(对象)
我在 Array List
中填入了一些数字,并希望找到 Array List
中的特定数字并获取其在我的 Array List
中的位置(索引)。
任何例子都很好!
例如
ProClon.indexOf(spro.getId(id));
检查arrayList的api。 indexOf(对象o);做你需要的。 http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
首先用指定字段覆盖 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));
只需在数组中使用方法 indexOf arrayName.indexOf(对象)