I have created an ArrayList of class Student. I have added four objects and then I removed one of the object. However, when I print the list all the four objects are displayed. I am not able to understand why?
Here's my code.
import java.util.ArrayList;
import java.util.List;
class Student1 {
private String name;
private int age;
Student1(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Student[" + name + ", " + age + "]";
}
}
public class Test1 {
public static void main(String[] args) {
List<Student1> students = new ArrayList<>();
students.add(new Student1("ABC", 25));
students.add(new Student1("XYZ", 27));
students.add(new Student1("PQR", 26));
students.add(new Student1("LMN", 28));
students.remove(new Student1("ABC", 25));
for (Student1 stud : students) {
System.out.println(stud);
}
}
}
Output of my code is as given below.
Student[ABC, 25]
Student[XYZ, 27]
Student[PQR, 26]
Student[LMN, 28]