Aug 5 2010

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?

Continue reading


Sep 13 2007

Google releases some nice code…

Google Guice is a really great Dependency Injection Framework and worth a look. Especially the performance and – much more important – the configuration using Java code in a very intuitive form are great features.

They have now released another project that can be very, very helpful. It is called Google Collections and provides some small but helpful classes.

A series describing the details can be found here:
http://publicobject.com/2007/09/coding-in-small-with-google-collections_08.html