i have a class called Student has two variables:
String lastName;
String firstName;
public Student(String lastName,String firstName){
this.lastName = lastName;
this.firstName = firstName;
}
public Student(String lastName){
this.lastName = lastName;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
String getLastName = ((Student) obj).getLastName();
return lastName.equalsIgnoreCase(getLastName);
}
in the Main class i have created an ArrayList
private static ArrayList<Student> listOfStudents = new ArrayList<>();
and i have created this method to get the students from ArrayList
public void findStudent(String lastName){
for (int i=0;i<listOfStudents.size();i++){
if (listOfStudents.get(i).equals(new Student(lastName))){
System.out.println(listOfStudents.get(i));
}
}
}
I have overridden equals() to check by last name. Now everything is well, but when i add duplicate last name like below:
listOfStudents.add(new Student("Tamoussat","Abdelillah"));
listOfStudents.add(new Student("Tamoussat","Fatima"));
listOfStudents.add(new Student("Soussi","Ahlam"));
I get only the first element, i want the way of how to get more than one element if they have the same last name? Best Regards