有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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。提前谢谢


共 (4) 个答案

  1. # 1 楼答案

    您只需返回索引(i

     return i;
    

    在找到它等于后,您不再试图找到不正确的i索引,您应该通过id找到student的索引,但您已经这样做了,并且发现它位于索引i

    注意:当您在查找元素时选择不中断循环,而是返回索引时,index变量是无用的

  2. # 2 楼答案

    你说你的目标是

    find the index of student object through their ID attribute through an arraylist

    我建议您只需在Student类中实现equals方法,当且仅当两个Student实例具有相同的id时,它才会返回true,然后只需使用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);
    }
    
  3. # 3 楼答案

    你犯了一个概念上的错误。实际上:

    studentArray.indexOf( elem );
    

    返回数组中元素elem的索引,但elem应属于学生类。当然,只要这个类提供了一个“equals”方法。在您的情况下,类似于:

    @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 );
    

    正在尝试在学生数组(studentArray)中查找整数(i)

    另一种方法是返回职位,如下所示:

    return i;
    

    干杯

  4. # 4 楼答案

    在findIndex()方法中,替换此行

              return index = studentArray.indexOf(i);
    

              return i ;