Topic12ADTS GenericDataStructures
Topic12ADTS GenericDataStructures
CS 307 Fundamentals of 6
Computer Science ADTs and Data Structures
Data Structures in Java
Part of the Java Standard Library is the
Collections Framework
– In class we will create our own data structures
and discuss the data structures that exist in Java
A library of data structures
Built on two interfaces
– Collection
– Iterator
http://java.sun.com/j2se/1.5.0/docs/guide/
collections/index.html
CS 307 Fundamentals of 7
Computer Science ADTs and Data Structures
The Java Collection interface
A generic collection
Can hold any object data type
Which type a particular collection will hold is
specified when declaring an instance of a
class that implements the Collection interface
Helps guarantee type safety at compile time
CS 307 Fundamentals of 8
Computer Science ADTs and Data Structures
Methods in the Collection interface
public interface Collection<E>
{ public boolean add(E o)
public boolean addAll(Collection<? extends E> c)
public void clear()
public boolean contains(Object o)
public boolean containsAll(Collection<?> c)
public boolean equals(Object o)
public int hashCode()
public boolean isEmpty()
public Iterator<E> iterator()
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
public boolean retainAll(Collection<?> c)
public int size()
public Object[] toArray()
public <T> T[] toArray(T[] a)
}
CS 307 Fundamentals of 9
Computer Science ADTs and Data Structures
The Java ArrayList Class
Implements the List interface and uses an
array as its internal storage container
It is a list, not an array
The array that actual stores the elements of
the list is hidden, not visible outside of the
ArrayList class
all actions on ArrayList objects are via the
methods
ArrayLists are generic.
– They can hold objects of any type!
CS 307 Fundamentals of 10
Computer Science ADTs and Data Structures
ArrayList's (Partial)
Class Diagram
Iterable
Object Collection
AbstractCollection
List
AbstractList
ArrayList
CS 307 Fundamentals of 11
Computer Science ADTs and Data Structures
Back to our Array Based List
Started with a list of ints
Don't want to have to write a new list class
for every data type we want to store in lists
Moved to an array of Objects to store the
elements of the list
// from array based list
private Object[] myCon;
Elsewhere
ArrayList<String> list3 = new ArrayList<String>();
printFirstChar( list3 ); // ok
ArrayList<Integer> list4 = new ArrayList<Integer>();
printFirstChar( list4 ); // syntax error
CS 307 Fundamentals of ADTS and Generic Data Structures 26
Computer Science
Generic Types and Subclasses
ArrayList<ClosedShape> list5 =
new ArrayList<ClosedShape>();
list5.add( new Rectangle() );
list5.add( new Square() );
list5.add( new Circle() );
// all okay
list5 can store ClosedShapes and any
descendants of ClosedShape