Created
September 29, 2010 11:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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