July 19, 2005
Another reason why Lists beat Arrays and Generics are useful
Here's one of many reasons why Java generics do not suck: With generics we may finally forego arrays[] in favour of the List, which will ultimately make all of us better people. Not only can Lists grow and shrink on demand, they can also be smart about managing their own contents, and do not need a container to do it for them.
Say you're writing a class that holds a set of EventListeners and offers public methods to manipulate that set. This is the sort of clutter we used to produce for that simple job:
List eventListeners = new ArrayList();
public EventListener[] getEventListeners() {
return (EventListener[])eventListeners.toArray();
}
public void addEventListener(EventListener el) {
eventListeners.add(el);
}
public void removeEventListener(EventListener el) {
eventListeners.remove(el);
}
Repeat that for any multiplicity-many reference in your code and you know where these line counts are going. Now that we have typesafe collections, we only need one method that might as well return our actual List:
List<EventListener> eventListeners = new ArrayList<EventListener>();
public List<EventListener> getEventListeners() {
return eventListeners;
}
Should we later need to run funky code whenever a new EventListener is added, we can make our List aware of that:
List<EventListener> eventListeners = new ArrayList<EventListener>() {
public boolean add(EventListener el) {
super.add(el);
// funky code goes here!
}
};
I actually do not use ArrayList for a job like this, but a custom implementation of List that can only be manipulated using add and remove and throws an UnsupportedOperationException in response to anything else.
Because the returned List is an actual object we may pass it on to other methods, which can manipulate it without knowledge of the containing class. This alone allowed me to remove several pages of code today.
Arrays. What have they ever done for you? Switch to Lists and join me in parameterized Nirvana.
Comments
Wow, Java introduces lists as type-safe, first-class objects? Cool!
Now, where did I hear about those before… ;-)
Posted by Aristotle Pagaltzis (#)
It took long enough, did it? If it wasn't for the massive number of legacy APIs still living on arrays, I could have so much more fun though.
Posted by
Henning Koch
(#)