Imogen Thompson
Imogen Thompson

Reputation: 11

Removing objects from ArrayList in java which are used in other classes

I have an ArrayList of instructors in my School class. I also have an Administrator class which is attached to the School class. I would like to randomly remove instructors from the school from within the Administrator class. Here is my code:

public void instructorMayLeave(){
    Iterator<Instructor> instructorIterator = school.getInstructors().iterator();
    while (instructorIterator.hasNext()){
        Instructor instructor = instructorIterator.next();
        int chanceOfLeaving = random.nextInt(100);
        if(chanceOfLeaving < 20){
            instructorIterator.remove();
        }
    }
}

However I don't think that instructors are actually being removed from the School class. Can anyone help me with this?

Upvotes: 0

Views: 44

Answers (1)

Anonymous
Anonymous

Reputation: 86343

It depends on what precisely getInstructors() does.

  • It may return a copy of the liist of instructors. If so, your code only removes instructors from the copy, not from the school. In this case you need the school to have a removeInstructor method or similar for you to call.
  • Or getInstructors() may return the list of instructors itself. In this case your code will remove instructors from the school’s list (depending on your random numbers, of course).

The former is considered the safe design. In this the school in the end itself can control removal of instructors. In the latter design, a client may keep a reference to the list indefinitely and add and remove instructors at any future time.

Upvotes: 2

Related Questions