Tuesday, 31 July 2012

Java Generics IV - Incompatible Types, Reifed

How to Solve: "Uncompilable source code - incompatible types"?


The following piece of code:
public class MyClass {

  public static class A {};

  protected HashSet<A> theSet = new HashSet<A>();

  public Set<Object> getSet() {
    return (Set<? extends Object>) theSet;
  }

  public static void main(String[] args) {
    MyClass mc = new MyClass();
    Set<Object> s = mc.getSet();
  }

}
generates the following error at compile time:

  test3/MyClass.java:[13,15] incompatible types
  found   : java.util.Set<capture#128 of ? extends java.lang.Object>
  required: java.util.Set<java.lang.Object>

The HashSet<A> cannot be cast into a Set<Object>. One needs to create an new Set<Object> and copy the content of HashSet<A> to it:
public Set<Object> getSet() {

  Set<Object> result = new HashSet<Object>();
  result.addAll(theSet);
  
  return result;

  // return (Set<? extends Object>) theSet;

}

What Does Reified Mean in the Context of Java Generics?

It means that if you define a Set<String> and a Set<Integer>, Java does not (directly) provide the mean to retrieve the type used to instantiate the generics. In other words, it is not (easily) possible to retrieve String and Integer when inspecting the sets at runtime.


Part I  Part II   Part III   Part IV