arraylist中的java查找索引始终位于1
我试图通过arraylist通过ID属性找到student对象的索引。然而,它总是出现-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"));
事实证明是真的。但在第一个类中,它显示为false并返回-1。提前谢谢
# 1 楼答案
您只需返回索引(i)
在找到它等于后,您不再试图找到不正确的i索引,您应该通过id找到student的索引,但您已经这样做了,并且发现它位于索引i
注意:当您在查找元素时选择不中断循环,而是返回索引时,
index
变量是无用的# 2 楼答案
你说你的目标是
我建议您只需在
Student
类中实现equals方法,当且仅当两个Student
实例具有相同的id
时,它才会返回true,然后只需使用indexOf method provided by ArrayListStudent
中的equals
方法可能如下所示:# 3 楼答案
你犯了一个概念上的错误。实际上:
返回数组中元素elem的索引,但elem应属于学生类。当然,只要这个类提供了一个“equals”方法。在您的情况下,类似于:
您在代码中使用以下行执行的操作:
正在尝试在学生数组(studentArray)中查找整数(i)
另一种方法是返回职位,如下所示:
干杯
# 4 楼答案
在findIndex()方法中,替换此行
与