简体   繁体   English

在 arraylist 中查找特定元素的 position

[英]Find position of specific element in arraylist

I have a class "Student".That stores the information of students name age mark etc. I'm using it in arraylist.我有一个 class “学生”。它存储学生姓名年龄标记等信息。我在 arraylist 中使用它。 Here I want to know the position of specific student.这里我想知道具体学生的position。 Is there any methods to find it or I have to use "for".please help me?有什么方法可以找到它或者我必须使用“for”。请帮助我?

Class student{
     String name; 
     Int age; 
      Int mark1; 
     Int mark2; 
     Public class student(String name,Int age, Int mark1, Int mark2){
      this.name=name;
      ...
      ...
          }
       
        }
    In the main function {
      Arraylist<student> ar=new Arraylist<student>();
      //Added some students detail using add method //

Then I have to find a position of the student using his name.然后我必须用他的名字找到学生的position。

The Java List interface has Java List 接口有

int indexOf(Object o) int indexOf(对象o)

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回 -1。

But that would require you to pass in a Student object to search for.但这需要你传入一个Student object 来搜索。

Thus: you have to somehow iterate the list, and do compare "manually".因此:您必须以某种方式迭代列表,并“手动”进行比较。

Of course, there are many different ways to do that.当然,有很多不同的方法可以做到这一点。 Using streams for example, you might be able to write very concise code do that.例如,使用,您可以编写非常简洁的代码来做到这一点。 But for newbies, just go step by step.但是对于新手来说,只是一步一步的 go。 First do a normal for loop, then try the "for each" version, then look into streams.首先做一个正常的for循环,然后尝试“for each”版本,然后查看流。

You can use indexOf method defined in the List<T> interface as mentioned before.您可以使用前面提到的List<T>接口中定义的indexOf方法。 Its signature looks like:它的签名看起来像:

int indexOf(Object o);

But you'll need to override the equals and hashCode methods of Object class in your Student class to use indexOf .但是您需要在Student class 中覆盖Object class 的equalshashCode方法才能使用indexOf

For example in例如在

class Student {

//... fields, methods and constructors, you already defined


  @Override
  public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      Student student = (Student) o;
      return age == student.age &&
              mark1 == student.mark1 &&
              mark2 == student.mark2 &&
              Objects.equals(name, student.name);
  }

  @Override
  public int hashCode() {
      return Objects.hash(name, age, mark1, mark2);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM