L15 Generics PDF
L15 Generics PDF
and the
Java Collections
Framework
Lecture 15
CS2110 – Fall 2011
Generic Types
2
Example
//removes all 4-letter words from c
//elements must be Strings
static void purge(Collection c) {
old
Iterator i = c.iterator();
while (i.hasNext()) {
if (((String)i.next()).length() == 4)
i.remove();
}}
Iterator<String> i = c.iterator();
while (i.hasNext()) {
if (i.next().length() == 4)
i.remove();
}}
3
Another Example
4
Type Casting
The Java compiler determines that the cast is not
necessary, based on the declared type
5
Autoboxing
Java 5 also introduced autoboxing and auto-unboxing
of primitive types, so the example can be further
simplified
Map<String,Integer> grades = new HashMap<String,Integer>();
grades.put("John",new Integer(67));
grades.put("Jane",new Integer(88));
grades.put("Fred",new Integer(72));
Integer x = grades.get("John");
sum = sum + x.intValue();
6
Using Generic Types
<T> is read, “of T”
For example: Stack<Integer> is read, “Stack of Integer”
7
Advantage of Generics
Declaring Collection<String> c tells us
something about the variable c (i.e., c holds only
Strings)
This is true wherever c is used
The compiler checks this and won’t compile code that
violates this
9
Programming with Generic Types
public interface List<E> { // E is a type variable
void add(E x);
Iterator<E> iterator();
}
10
Wildcards
void printCollection(Collection c) {
Iterator i = c.iterator();
old
while (i.hasNext()) {
System.out.println(i.next());
}}
void printCollection(Collection<Object> c) {
bad
for (Object e : c) {
System.out.println(e);
}}
good
void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}}
11
Bounded Wildcards
static void sort (List<? extends Comparable> c) {
...
}
12
Generic Methods
Adding all elements of an array to a Collection
static void a2c(Object[] a, Collection<?> c) {
bad
for (Object o : a) {
c.add(o); // compile time error
}}
for (T o : a) {
c.add(o); // ok
}}
13
Generic Classes
public class Queue<T> extends AbstractBag<T> {
15
Java Collections Framework
Collections: holders that Goal: conciseness
let you store and A few concepts that are broadly
useful
organize objects in
Not an exhaustive set of useful
useful ways for efficient concepts
access
The collections
Since Java 1.2, the framework provides
package java.util Interfaces (i.e., ADTs)
includes interfaces and Implementations
classes for a general
collection framework
16
JCF Interfaces and Classes
Interfaces Classes
Collection HashSet
Set (no duplicates) TreeSet
SortedSet ArrayList
List (duplicates OK) LinkedList
Iterator
Iterable
ListIterator
17
java.util.Collection<E>
(an interface)
public int size();
Return number of elements in collection
public boolean isEmpty();
Return true iff collection holds no elements
public boolean add(E x);
Make sure the collection includes x; returns true if collection has changed
(some collections allow duplicates, some don’t)
public boolean contains(Object x);
Returns true iff collection contains x (uses equals( ) method)
public boolean remove(Object x);
Removes a single instance of x from the collection; returns true if collection
has changed
public Iterator<E> iterator();
Returns an Iterator that steps through elements of collection
18
java.util.Iterator<E> (an interface)
19
Additional Methods of Collection<E>
20
java.util.Set<E> (an interface)
Set extends Write a method that
Collection checks if a given word is
Set inherits all its methods within a Set of words
from Collection
Write a method that
removes all words longer
A Set contains no
than 5 letters from a Set
duplicates
If you attempt to add() an
Write methods for the
element twice then the union and intersection of
second add() will return two Sets
false (i.e., the Set has not
changed)
21
Set Implementations
java.util.HashSet<E> (a hashtable)
Constructors
public HashSet();
public HashSet(Collection<? extends E> c);
public HashSet(int initialCapacity);
public HashSet(int initialCapacity, float loadFactor);
java.util.TreeSet<E>
(a balanced BST [red-black tree])
Constructors
public TreeSet();
public TreeSet(Collection<? extends E> c);
...
22
java.util.SortedSet<E> (an interface)
23
java.lang.Comparable<T> (an interface)
24
java.util.Comparator<T> (an interface)
25
SortedSet Implementations
java.util.TreeSet<E>
constructors:
public TreeSet();
public TreeSet(Collection<? extends E> c);
public TreeSet(Comparator<? super E> comparator);
...
26
java.util.List<E> (an interface)
List extends Collection
Items in a list can be accessed via their index (position in list)
The add() method always puts an item at the end of the list
The iterator() returns the elements in list-order
Methods (in addition to those inherited from Collection):
public E get(int index);
Returns the item at position index in the list
public E set(int index, E x);
Places x at position index, replacing previous item; returns the previous item
public void add(int index, E x);
Places x at position index, shifting items to make room
public E remove(int index);
Remove item at position index, shifting items to fill the space;
Returns the removed item
public int indexOf(Object x);
Return the index of the first item in the list that equals x (x.equals())
…
27
List Implementations
java.util.ArrayList<E> (an array; uses array-
doubling)
Constructors
public ArrayList();
public ArrayList(int initialCapacity);
public ArrayList(Collection<? extends E> c);
28
Efficiency Depends on Implementation
Object x = list.get(k);
O(1) time for ArrayList
O(k) time for LinkedList
list.remove(0);
O(n) time for ArrayList
O(1) time for LinkedList
if (set.contains(x)) ...
O(1) expected time for HashSet
O(log n) for TreeSet
29