Java Generics and Subtyping Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park
Which of these are legal? String s = new Object(); Object o = new String(); Set s1 = new HashSet(); Set s2 = new HashSet ();
Subtypes If B is a subtype of A, then a B can be used where an A is expected For example, if a method is declared to return an Object, you can return a String
Subtypes and Collections A HashSet is a subtype of Set String is a subtype of Object But a HashSet is not a subtype of HashSet and ArrayList > is not a subtype of List >
Why not?? void f(HashSet set) { ??? } void g(HashSet set) { f(set); for(String s : set) System.out.println(s.substring(0,1)); }
Why not?? void f(HashSet set) { set.add(new Integer(42)); } void g(HashSet set) { f(set); for(String s : set) System.out.println(s.substring(0,1)); }
Wildcards in generics This is somewhat advanced material, but useful You can define a function as: void f(Set set) {... } What does that mean? It means that f takes as a parameter a Set of some type that is unnamed and unknown So the Set passed to f might be a Set, or a Set, or a Set >, or...
yes, but what does that mean If f is defined to take a Set set Then set is a read-only set You can take a value out; the only thing you know about it is that what you take out is some subtype of Object But you can’t add a value to set You don’t know what the type of things you are allowed to add to set is
This can get more complicated If you define void f(Set > set) Can pass to f: HashSet >
Arrays and Subtyping public class Test2 { public static void f(Object a[]) { System.out.println(a[0]); } public static void g(Object a[]) { a[0] = new Integer(17); } public static void main(String[] args) { String[] s = {"a", "b"}; f(s); // OK g(s); }
Markov Chain Sunny DayCloudy Day 90% 50% 10%
Second Order Markov Chain Random Text Generation Project
Links FSM Generics - erics-tutorial.pdf erics-tutorial.pdf