Java Generics and Subtyping Nelson Padua-Perez Bill Pugh Department of Computer Science

Download Report

Transcript Java Generics and Subtyping Nelson Padua-Perez Bill Pugh Department of Computer Science

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<String> s2
= new HashSet<String>();
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<String> is a subtype of Set<String>
String is a subtype of Object
But a HashSet<String> is not a subtype of
HashSet<Object>
and ArrayList<ArrayList<String>> is not a subtype of
List<List<String>>
Why not??
void f(HashSet<Object> set) {
???
}
void g(HashSet <String> set) {
f(set);
for(String s : set)
System.out.println(s.substring(0,1));
}
Why not??
void f(HashSet<Object> set) {
set.add(new Integer(42));
}
void g(HashSet <String> 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<Object>, or a
Set<String>, or a Set<Set<Integer>>, 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< ? extends Set<String> > set)
Can pass to f:
HashSet<HashSet<String>>
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
10%
Sunny Day
Cloudy Day
50%
90%
50%
Second Order Markov Chain
Random Text Generation Project
Links
FSM - http://www.mathmaniacs.org/lessons/fsm/frustrating.html
Generics http://www.cs.umd.edu/class/spring2006/cmsc132/Documents/gen
erics-tutorial.pdf