views:

42

answers:

1

I have a code piece that looks something like what I've pasted below:

import java.util.LinkedHashMap;
import java.util.Map;

public class GenericMagic {
  GenericMagic() {
  }


  private class Container {
    int doSomething(){ return 42;}

    @Override
    public String toString() {
      return "Container"+doSomething();
    }
  }

  private class TheCache<String, Container> extends LinkedHashMap<String, Container> {
    @Override
    protected boolean removeEldestEntry(Map.Entry<String, Container> eldest) {
      Container value = eldest.getValue();
      value.doSomething();//if I comment this out it compiles
      System.out.println(value);
      return false;
    }
  }
}

In my 'TheCache' class, I want to constrain the generic type to a specific, which is fine, but when I get the 'value' as a Container, it is somehow not typed, in that I cannot execute the doSomething method. Why?

A: 

Just get rid of the <String, Container> bit in the class declaration:

private class TheCache extends LinkedHashMap<String, Container> {

It was treating "String" and "Container" as if they were the generic type identifiers (typically "T"). So it didn't know that the Container to which you were referring was your nested class.

Carl Manaster
Yeah I figured it out myself :/ Sometimes I'm just too clever for my own good.
Kylar
Figuring stuff out is never bad! :-)
Carl Manaster