2006-07-15

Regaining a name for a wildcard type

When using generics I run into the same problem over and over: a class has a field of a parameterized type but actually doesn't care about the type. A perfect match for using wildcards. However, within a method the using class needs to call methods of the parameterized type that have arguments of the type parameter - of course just derived from that very object. For example: rotate a linked list.

public class RotateList {
  LinkedList<?> theList;

  public void rotate() {
    LinkedList<?> l = theList;
    theList.addLast(theList.removeFirst());
  }
}

This does not compile since an important piece of information is lost between calling removeFirst and addLast: not only don't we know the type of the result but we also don't know that it's the very type parameter of the list we're talking about.

At this point I would normally resign and propagate the list's type parameter to the using class. This way, type parameters spread throughout my code. But there is hope! We can pull out the code into a generic method, parameterized by the list's element type. This way we can give a local name to the wildcard that will convince the compiler that we're doing right:

public class RotateList {
  LinkedList<?> theList;

  public void rotate() {
    // what used to be an unknown type
    // regains a name in the method
    // and becomes more useful
    rotate(theList);
  }

  private <T> void rotate(LinkedList<T> l) {
    l.addLast(l.removeFirst());
  }
}

Probably not a surprise for generics wizards but I had my aha-moment! Now why do we need an extra method? How about a syntax for introducing a type name within a method?

public class RotateList {
  LinkedList<?> theList;

  public void rotate() {
    <T> List<T> l = theList;
    l.addLast(l.removeFirst());
  }
}
Posted by Matthias at 9:37.43. Comment: blog@mernst.org
Edited on: 2006-07-15 9:47.27

2006-07-05

Defeated

We just got our asses kicked 2:0 in the last three minutes. Trotzdem, Jungs, Ihr wart großartig! Dann fahren wir halt nach Stuttgart.
Posted by Matthias at 24:54.09. Comment: blog@mernst.org
Edited on: 2006-07-07 8:53.10

2006-07-04

Seattle Pictures

I spent a few days in Seattle last week. The city sported some fabulous weather - thanks! Here's some pictures:
Posted by Matthias at 3:26.30. Comment: blog@mernst.org
Edited on: 2006-07-04 3:27.57

2006-07-03

OSVM in trouble

Esmertec is closing its Denmark subsidiary after having CTO, CEO and two co-founders leave and a dramatic loss in revenue (press releases). Sad news since Lars Bak and his team were building OSVM, a highly interesting Smalltalk environment for embedded devices. Hopefully it doesn't just go away. (via Christian Plesner Hansen).
Posted by Matthias at 9:55.14. Comment: blog@mernst.org