Reputation: 11
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
Reputation: 86343
It depends on what precisely getInstructors()
does.
removeInstructor
method or similar for you to call.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