Skip to content

Instantly share code, notes, and snippets.

@davidsheldon
Created September 29, 2010 11:16
Show Gist options
  • Select an option

  • Save davidsheldon/602571 to your computer and use it in GitHub Desktop.

Select an option

Save davidsheldon/602571 to your computer and use it in GitHub Desktop.
Example of generics needing an extra, hacky, method in order to bind a type for a block.
import java.util.ArrayList;
import java.util.List;
public class GenericsExample {
public static class CollectionWrapper<T> {
private List<T> stuff;
public List<T> getStuff() {
return stuff;
}
public void setStuff(List<T> newStuff) {
stuff = newStuff;
}
}
public static void main() {
List<CollectionWrapper<?>> foo = new ArrayList<CollectionWrapper<?>>();
foo.add(new CollectionWrapper<String>());
foo.add(new CollectionWrapper<Long>());
for(CollectionWrapper<?> a: foo) {
// This would fail to compile.
// a.setStuff(a.getStuff());
hackGenerics(a);
}
}
// This binds the type <T> to the wrapper, so that it knows that
// the <T> it gets back from getStuff is the same type that setStuff wants.
private static <T> void hackGenerics(CollectionWrapper<T> wrapper) {
wrapper.setStuff(wrapper.getStuff());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment