Atom Feed SITE FEED   ADD TO GOOGLE READER

A super() Java Language Hack

I'm creating an EventList called PopularityList that will sort elements by the number of times they occur in the source EventList. I'm extending TransformedList, which has a single protected constructor with the signature:
protected TransformedList(EventList source);

To implement PopularityList:
  • First I create a UniqueList of the source EventList's elements.
  • Wrap that UniqueList in a SortedList, sorting by the number of duplicates in the UniqueList

    But when I combined these two problems in the most natural way, I had a problem:
    private UniqueList ul = null;

    public PopularityList(EventList source) {
    super(new SortedList(new UniqueList(source), new PopularityComparator());
    ...
    }


    The problem is that my PopularityList class needs to keep a reference to the UniqueList object created in the constructor. But the two obvious attempts fail to compile. The first solution fails due to "cannot reference ul before supertype constructor has been called":
    private UniqueList ul = null;

    public PopularityList(EventList source) {
    super(new SortedList(ul = new UniqueList(source), new PopularityComparator());
    ...
    }


    The second solution is a very slight variation that fails due to "')' expected":
    private UniqueList ul = null;

    public PopularityList(EventList source) {
    super(new SortedList(UniqueList temp = new UniqueList(source), new PopularityComparator());
    ul = temp;
    ...
    }


    So what did I do next? I paniced! But that got boring so I came up with a clever hack. I created a private constructor that has a parameter for each object that I need to keep a reference to, then I called this(). It works perfectly:
    private UniqueList ul = null;

    public PopularityList(EventList source) {
    this(source, new UniqueList(source));
    }
    private PopularityList(EventList source, UniqueList uniqueList) {
    super(new SortedList(uniqueList, new PopularityComparator()));
    this.ul = uniqueList;
    ....
    }
  • omg you are so brilliant!!!!
    hehehe
    fuck your ass