Java Surprise: Setters/Getters and Collections
Inspired by the Java Killers series, I wanted to post a problem I stumbled across some years ago:
Imagine a bean containing a field.
class Car {
private final List tires = new ArrayList();
public void setTires( List tires ) {
this.tires.clear();
this.tires.addAll( tires );
}
public void addTire( Tire tires ) {
this.tires.add( tires );
}
public List getTires() {
return Collections.unmodifiableList( tires );
}
}
What is the output of that code?
Car car = new Car(); car.addTire( new Tire() ); car.addTire( new Tire() ); List carTires = car.getTires(); System.out.println( "before: " + carTires.size() ); car.setTires( carTires ); System.out.println( "after1: " + car.getTires().size() ); System.out.println( "after2: " + carTires.size() );
The first part is easy:
before: 2
But the rest?