How to add elements to an object list in java

Viewed 90
public class Bus{
    private int seats;
    private List<People> currentPeople;
    
    public Bus(int seats){
      this.seats = seats;
    }
    
    public void passengers(List<People> boarders, List<People> deboarders){
    this.currentPeople.remove(deboarders);
    this.currentPeople.add(boarders);
    }

I'm trying to create a list of people on the bus. I'm trying to remove deboarders(alighting passengers) from the list and add the boarders(boarding passengers). But Java won't let me add the boarders to the currentPeople list. People is a class which stores the name and ticket number of the passanger. Any help on this? I've been trying to solve this for hours.

3 Answers

To add a collection of objects to a list you need to use addAll:

this.currentPeople.addAll(boarders);

To remove a collection of objects from a list you need to use removeAll:

this.currentPeople.removeAll(deboarders);

Be careful, in order to compare and remove the right elements from the list, removeAll uses equals method. So you should implement equals method in your People class.

EDIT:

equals method for People class:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        People people = (People) o;

        if (ticketNumber != people.ticketNumber) return false;
        return name != null ? name.equals(people.name) : people.name == null;
    }

Don't forget to initialize currentPeople list, otherwise you will get NullPointerException.

Change add to addAll and likewise for remove.
As Federico points out in comments, assuming People has equals method implemented.

Try removeAll() and addAll() methods because you are passing a Collection as a parameter.

Do not forget " ; " at the end of the line inside your constructor.

this.currentPeople.removeAll(deboarders);
this.currentPeople.addAll(boarders);
Related