-1

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]
  • Read the **documentation**, i.e. the javadoc of [`remove(Object)`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-), which says that it will remove the element where `equals()` returns `true`. Since you did not implement `equals()`, your two `Student1("ABC", 25)` objects are not equal to each other. – Andreas Dec 09 '20 at 07:36

2 Answers2

1

Your class Student should have equals method.

@Override
public boolean equals(Object other) {
    if (!(other instanceof Student)) {
        return false;
    }
    Student otherStudent = (Student) other;
    return this.name.equals(otherStudent.name) && this.age == otherStudent.age;
}

As by default equals method only check if other Object is reference of same object.

this == other

So your original code works correctly only with following example:

List<Student1> students = new ArrayList<>();
Student student = new Student("ABC", 25);
students.add(student);
students.remove(student);

In java equality of objects is compared with equals method.

elehtine
  • 106
  • 5
1

I think that the problem is that you try to remove a new object that don't exist. Try to create new objects out of the adding method.

    Student1 stu=new Student1("ABC", 25);
    students.add(stu);

    students.remove(stu);