'IndexOf from an array shows as a negative number in an arraylist

class Main{
int index = Student.studenten.indexOf(loggedInId);
}

Here in the main class im trying to get the position of the variable loggedInId which is an int.

class Student{
static ArrayList<Student>studenten = new ArrayList<>();

 public Student(int id, String naam, int studentnummer, String wachtwoord, boolean docent){
studenten.add(new Student(1,"Rowan", 21069816, "test", true));
        studenten.add(new Student(2,"test", 1234567, "test", false));
   }
}

Im adding the students to the arraylist with their id etc.

What im trying to do is have their id searched for position (for example id = 1) then it will look the position of that id in the arraylist (which would be position 0) and then return the position for the int index. So that i can get their studentnummer with that index.

Basically im trying to find their studentnummer with only their id

But no matter if loggedInId is 1 or 2, it will always return as -1 and that is out of bounds.



Solution 1:[1]

better use a map instead of a list, you can do something like :-

class Student {
private int id;
private int studentnummer;

static Map<Integer, Student> studenten = new HashMap<>();

public Student(int id, String naam, int studentnummer, String wachtwoord, boolean docent) {
    this.id = id;
    this.studentnummer = studentnummer;
    Student std1 = new Student(1, "Rowan", 21069816, "test", true);
    Student std2 = new Student(2, "test", 1234567, "test", false);
    studenten.put(std1.id, std1);
    studenten.put(std2.id, std2);
}

}

To get the student by id :-

 int stdToSearch = 1;
 Student student = 
 Student.studenten.get(stdToSearch);nummer=student.getStudentnummer();

Solution 2:[2]

I think you are using the wrong function. The indexOf(element) function needs an element as a parameter (in your case a Student). After getting the parameter it checks if that element exists in the array.

If the element exists in the array it will return the index of where exactly in the array it is located.

If the element DOES NOT exist it will always return -1;

If what you are trying to do is get a user with a specific ID:

make a foreach loop. In the foreach loop check if the current element(current student) in the arrayList has an ID of the Id that you are searching for.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Navneet agarwal
Solution 2 Nikola Develops