0

I was wondering how is it possible to remove an object from array list using a String. For example I have a class with Students and when I call the remove method I input Name and Last name and the method removes that student from the ArrayList.

I already made a method using exception, but always get the exception

public Student rmv(String name, String lname) throws MyException{
    if(students.contains(new Student(name, lname))){
        students.remove(new Student(name, lname));
    }else{
        throw new MyException("Doesn't exist");
    }
    return null;
}

2 Answers2

3

For this you need to override equals method. Where in that name and lname fields must be checked.

@Override
public boolean equals(Object obj) 
{

   return firstName.equals(obj.firstName) &&  lastName.equals(obj.lastName);
}

If you don't override it then each Student object created using new shall be different. And after inserting an element into list, you will never be able to get that ever.

SacJn
  • 777
  • 1
  • 6
  • 16
0

contains() checks whether particular object exists in the list through equals() method. So You have to override equals() method of Student class

@Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        return this.firstName.equals(obj.firstName) && this.lastName.equals(obj.lastName);
    }
Rahman
  • 3,755
  • 3
  • 26
  • 43