-1

I have a class "Student".That stores the information of students name age mark etc. I'm using it in arraylist. Here I want to know the position of specific student. Is there any methods to find it or I have to use "for" .please help me?

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.

  • 2
    See [`ArrayList#indexOf(Object o)`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-). – maloomeister Dec 08 '20 at 14:01
  • Does this answer your question? [Better way to find index of item in ArrayList?](https://stackoverflow.com/questions/8439037/better-way-to-find-index-of-item-in-arraylist) – leonardkraemer Dec 08 '20 at 14:02
  • Indexof requires a object. Should the object contain name,age,mark1,mark2 or Is it enough to have a name only? Because I'm asking what if I have students name only. – Ravindranath Tagore Dec 08 '20 at 14:13

2 Answers2

0

The Java List interface has

int indexOf(Object 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.

But that would require you to pass in a Student object to search for.

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. First do a normal for loop, then try the "for each" version, then look into streams.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You can use indexOf method defined in the List<T> interface as mentioned before. 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.

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