Download presentation
Presentation is loading. Please wait.
1
Java Generics and Subtyping Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park
2
Which of these are legal? String s = new Object(); Object o = new String(); Set s1 = new HashSet(); Set s2 = new HashSet ();
3
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
4
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 >
5
Why not?? void f(HashSet set) { ??? } void g(HashSet set) { f(set); for(String s : set) System.out.println(s.substring(0,1)); }
6
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)); }
7
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...
8
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
9
This can get more complicated If you define void f(Set > set) Can pass to f: HashSet >
10
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); }
11
Markov Chain Sunny DayCloudy Day 90% 50% 10%
12
Second Order Markov Chain Random Text Generation Project
13
Links FSM - http://www.mathmaniacs.org/lessons/fsm/frustrating.html http://www.mathmaniacs.org/lessons/fsm/frustrating.html Generics - http://www.cs.umd.edu/class/spring2006/cmsc132/Documents/gen erics-tutorial.pdf http://www.cs.umd.edu/class/spring2006/cmsc132/Documents/gen erics-tutorial.pdf
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.