Lecture Slides on Generic Types and the Java Collections Framework | CS 2110, Study notes of Computer Science

Material Type: Notes; Class: Object-Oriented Programming and Data Structures; Subject: Computer Science; University: Cornell University; Term: Summer 2008;

Typology: Study notes

Pre 2010

Uploaded on 08/30/2009

koofers-user-1eu
koofers-user-1eu 🇺🇸

9 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Generic Types and the
Java Collections
Framework
Lecture 17
CS2110 – Summer 2008
2
Announcements
yA4 posted, due Wed 6PM
yA3 grades posted
Regrade requests due Thursday, 11:59PM [check this]
yQuestions by Email
Faster responses if email class list, or ALL staff members
3
Java Collections Framework
yCollections: holders that let you store and organize objects i n useful
ways for efficient access
ySince Java 1.2, the package java.util includes interfaces and
classes for a general collection framework
yGoal: conciseness
A few concepts that are broadly useful
Not an exhaustive set of useful concepts
yTwo types of concepts are provided
Interfaces (i.e., ADTs)
Implementations
4
JCF Interfaces and Classes
yInterfaces
Collection
Set (no duplicates)
SortedSet
List (duplicates OK)
Map (i.e., Dictionary)
SortedMap
Iterator
Iterable
ListIterator
yClasses
HashSet
TreeSet
ArrayList
LinkedList
HashMap
TreeMap
5
Collections in Java <5
yBefore Java 1.5, collections had to b e implemented as
collections of type Object
So when extracting an element, had to downcast it to T
before we could invoke T's methods
Compiler could not check that the cast was correct at
compile-time, since it didn't know what T was
This was inconvenient and unsafe, could fail at runtime
6
Collections in Java <5
class ArrayStack implements Stack {
private Object[] array; //Array that holds the Stack
private int index = 0; //First empty slot in Stack
public ArrayStack (int maxSize)
{ array = new Object[maxSize]; }
public void push(Object x) { array[index++] = x; }
public Object pop() { return array[--index]; }
public Object peek() { return array[index-1]; }
public boolean isEmpty() { return index == 0; }
public void makeEmpty() { index = 0; }
}
class TestArrayStack {
public static void main( String [] args ) {
ArrayStack stack = new ArrayStack(100);
stack.push( new Integer(17) );
stack.push( “okay” );
String str = (String) stack.pop(); // downcast works
String bad = (String) stack.pop(); // runtime error!
}
pf3
pf4
pf5

Partial preview of the text

Download Lecture Slides on Generic Types and the Java Collections Framework | CS 2110 and more Study notes Computer Science in PDF only on Docsity!

Generic Types and the

Java Collections

Framework

Lecture 17

CS2110 – Summer 2008

2

Announcements

y A4 posted, due Wed 6PM

y A3 grades posted

ƒ Regrade requests due Thursday, 11:59PM [check this]

y Questions by Email

ƒ Faster responses if email class list, or ALL staff members

3

Java Collections Framework

y Collections: holders that let you store and organize objects in useful

ways for efficient access

y Since Java 1.2, the package java.util includes interfaces and

classes for a general collection framework

y Goal: conciseness

ƒ A few concepts that are broadly useful ƒ Not an exhaustive set of useful concepts

y Two types of concepts are provided

ƒ Interfaces (i.e., ADTs) ƒ Implementations

4

JCF Interfaces and Classes

y Interfaces

ƒ Collection

ƒ Set (no duplicates)

ƒ SortedSet

ƒ List (duplicates OK)

ƒ Map (i.e., Dictionary)

ƒ SortedMap

ƒ Iterator

ƒ Iterable

ƒ ListIterator

y Classes

ƒ HashSet

ƒ TreeSet

ƒ ArrayList

ƒ LinkedList

ƒ HashMap

ƒ TreeMap

Collections in Java <

y Before Java 1.5, collections had to be implemented as

collections of type Object

ƒ So when extracting an element, had to downcast it to T

before we could invoke T's methods

ƒ Compiler could not check that the cast was correct at

compile-time, since it didn't know what T was

ƒ This was inconvenient and unsafe, could fail at runtime

Collections in Java <

class ArrayStack implements Stack {

private Object[] array; //Array that holds the Stack private int index = 0; //First empty slot in Stack

public ArrayStack (int maxSize) { array = new Object[maxSize]; }

public void push(Object x) { array[index++] = x; } public Object pop() { return array[--index]; } public Object peek() { return array[index-1]; } public boolean isEmpty() { return index == 0; } public void makeEmpty() { index = 0; } }

class TestArrayStack { public static void main( String [] args ) { ArrayStack stack = new ArrayStack(100); stack.push( new Integer(17) ); stack.push( “okay” );

String str = (String) stack.pop(); // downcast works String bad = (String) stack.pop(); // runtime error! }

7

Generic Types in Java 5

y When using a collection we generally have a single type T of

elements that we store in it

ƒ e.g. LinkedList of Integers, HashSet of Strings, etc.

y Generics in Java 1.5 provide a way to communicate T, the type of

elements in a collection, to the compiler

ƒ Compiler can check that you have used the collection consistently

ƒ Result: safer and more efficient code

y Underlying motivation: we want to detect as many bugs as

possible at compile-time

8

Example

//removes 4-letter words from c //elements must be Strings static void purge(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) { if (((String)i.next()).length() == 4) i.remove(); }}

//removes 4-letter words from c static void purge(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) { if (i.next().length() == 4) i.remove(); }}

old

new

9

Another Example

Map grades = new HashMap(); grades.put("John",new Integer(67)); grades.put("Jane",new Integer(88)); grades.put("Fred",new Integer(72)); Integer x = (Integer)grades.get("John"); sum = sum + x.intValue();

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();

old

new

10

Type Casting

y In effect, Java inserts the correct cast automatically, based on the

declared type

y In this example, grades.get("John") is automatically cast to

Integer

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();

An Aside: Autoboxing

y Java 5 also has 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());

Map<String,Integer> grades = new HashMap<String,Integer>(); grades.put("John", 67); grades.put("Jane", 88); grades.put("Fred", 72); sum = sum + grades.get("John");

Using Generic Types

y is read, “of T”

ƒ For example: Stack is read, “Stack of Integer”

y The type annotation informs the compiler that all

extractions from this collection should be automatically

cast to T

y Specify type in declaration, can be checked at compile

time

ƒ Can eliminate explicit casts

19

Generic Methods

y Adding all elements of an array to a Collection

y See the online Java Tutorial for more information on generic

types and generic methods

static void a2c(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // compile time error }}

static void a2c(T[] a, Collection c) { for (T o : a) { c.add(o); // ok

good}}

bad

20

Java Collections Framework

y Collections: holders that let you store and organize objects in

useful ways for efficient access

y Since Java 1.2, the package java.util includes interfaces and

classes for a general collection framework

y Goal: conciseness

ƒ A few concepts that are broadly useful

ƒ Not an exhaustive set of useful concepts

y Two types of concepts are provided

ƒ Interfaces (i.e., ADTs)

ƒ Implementations

21

JFC Interfaces and Classes

y Interfaces

ƒ Collection

ƒ Set (no duplicates)

ƒ SortedSet

ƒ List (duplicates OK)

ƒ Map (i.e., Dictionary)

ƒ SortedMap

ƒ Iterator

ƒ Iterable

ƒ ListIterator

y Classes

ƒ HashSet

ƒ TreeSet

ƒ ArrayList

ƒ LinkedList

ƒ HashMap

ƒ TreeMap

22

Interface java.util.Collection

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 iterator();

ƒ Returns an Iterator that steps through elements of collection

Interface java.util.Iterator

public boolean hasNext();

ƒ Returns true if the iteration has more elements

public E next();

ƒ Returns the next element in the iteration

ƒ Throws NoSuchElementException if no next element

public void remove();

ƒ The element most-recently returned by next() is removed from the

collection

ƒ Throws IllegalStateException if next() not yet used or if

remove() already called

ƒ Throws UnsupportedOperationException if remove() not

supported

Additional Methods of Collection

public Object[] toArray()

ƒ Returns a new array containing all the elements of this collection

public T[] toArray(T[] dest)

ƒ Returns an array containing all the elements of this collection; uses

dest as that array if it can

Bulk Operations:

ƒ public boolean containsAll(Collection<?> c); ƒ public boolean addAll(Collection<? extends E> c); ƒ public boolean removeAll(Collection<?> c); ƒ public boolean retainAll(Collection<?> c); ƒ public void clear();

25

Interface java.util.Set

y Set extends Collection

ƒ Set inherits all its methods from Collection

y A Set contains no duplicates

ƒ If you attempt to add() an element twice then the second

add() will return false (i.e., the Set has not changed)

26

Set Implementations

y java.util.HashSet (a hashtable)

ƒ Constructors

public HashSet(); public HashSet(Collection<? extends E> c); public HashSet(int initialCapacity); public HashSet(int initialCapacity, float loadFactor);

y java.util.TreeSet (a balanced BST)

ƒ Constructors

public TreeSet(); public TreeSet(Collection<? extends E> c); ...

27

Interface java.util.SortedSet

y SortedSet extends Set

y For a SortedSet, the iterator() returns the

elements in sorted order

y Methods (in addition to those inherited from Set):

ƒ public E first();

Š Returns the first (lowest) object in this set

ƒ public E last();

Š Returns the last (highest) object in this set

ƒ public Comparator<? super E> comparator();

Š Returns the Comparator being used by this sorted set if there

is one; returns null if the natural order is being used

28

Interface java.lang.Comparable

y public int compareTo (T x);

ƒ Returns a value (< 0), (= 0), or (> 0)

Š (< 0) implies this is before x

Š (= 0) implies this.equals(x) is true

Š (> 0) implies this is after x

y Many classes implement Comparable

ƒ String, Double, Integer, Char, java.util.Date,…

ƒ If a class implements Comparable then that is considered to

be the class’s natural ordering

Interface java.util.Comparator

y public int compare(T x1, T x2);

ƒ Returns a value (< 0), (= 0), or (> 0)

Š (< 0) implies x1 is before x

Š (= 0) implies x1.equals(x2) is true

Š (> 0) implies x1 is after x

y Can often use a Comparator when a class’s natural

order is not the one you want

ƒ String.CASE_INSENSITIVE_ORDER is a predefined

Comparator

ƒ java.util.Collections.reverseOrder() returns a

Comparator that reverses the natural order

SortedSet Implementations

y java.util.TreeSet

ƒ This is the only class that implements SortedSet

ƒ TreeSet’s constructors

public TreeSet(); public TreeSet(Collection<? extends E> c); public TreeSet(Comparator<? super E> comparator); ...