arraylist中的查找索引总是以-1 -1
问题描述:
我试图通过一个数组列表通过它的ID属性来找到学生对象的索引。然而它总是出现-1。arraylist中的查找索引总是以-1 -1
public int findIndex(String id) {
// boolean exists = studentArray.contains(id);
int index = 0;
for (int i = 0; i < studentArray.size(); i++) {
if (studentArray.get(i).getId().equals(id)) {
return index = studentArray.indexOf(i);
}
} return -1;
}
在我的演示
BodyBag bag = new BodyBag(3);
Student student = new Student("Joe","1234",3.5);
Student student2 = new Student("Jill", "5678",3.4);
Student student3 = new Student("Angelina","9101",4.0);
System.out.println(bag.studentArray.get(0).getId().contains("1234"));
但实际上出来为真。但在第一类中,它会以假为出现并返回-1。提前致谢。
答
你应该只返回
return i;
而不是发现它等于后,你再次尝试找到我这是不正确的索引,你应该找到的索引(i)学生的索引是它的ID,但你已经完成了,发现它在索引i。
注意:当您找到元素不会中断循环,而是返回索引时,您的index
变量无用。
答
你说你的目标是
发现学生对象通过其ID属性索引通过一个ArrayList
我建议你简单地实现你的Student
类中equals方法在这样的它返回true的方式当且仅当两个Student
实例具有相同的id
,然后简单地使用indexOf method provided by ArrayList
在Student
的equals
方法可能是这个样子:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return id == null ? other.id == null : id.equals(other.id);
}
答
你有一个概念上的错误。实际上:
studentArray.indexOf(elem);
返回元素 ELEM的索引数组中,但 ELEM应该是类学生的。当然,只要这个课程提供了一个“平等”的方法。在你的情况,是这样的:
@Override
public boolean equals(Object obj) {
// first you should check if obj is student before casting it...
Student aux = (Student) obj;
return this.getId().equals(aux.getId());
}
你在你的代码做什么用线:
return studentArray.indexOf(i);
试图寻找学生的数组中的整数(I)(studentArray) 。
做其他的方式,如贴在下面,是刚刚返回的位置,至极是:
return i;
干杯。
答
在你findIndex()方法,替换该行
return index = studentArray.indexOf(i);
与
return i ;
我不完全得到'studentArray.indexOf(I);' - 不会'i'已经是索引了?反正'studentArray'是什么?如果它是一个名称暗示的数组,则不应该有'indexOf()'方法。 – Thomas
在您的演示中,您没有将新创建的学生添加到BodyBag中。 –