You are on page 1of 77

Chapter 6

The Collections api


Introduction
• A data structure is a representation of data
and the operations allowed on that data.
• Data structures allow us to achieve
component reuse.
• Data structures store a collection of objects
and provide methods to add a new object to,
remove an existing object from, or access a
contained object in the collection.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2


Collection or Container
• A collection or a container is an object that
groups multiple elements into a single unit.
• Collections are used to store, retrieve,
manipulate, and communicate aggregate
data.
– Typically, collections represent data items that form a
natural group, such as a mail folder (a collection of
letters), or a telephone directory (a mapping of names
to phone numbers).
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-3
Collection: Example
Collection p1;
List a1 = new ArrayList();
if (p1.add(a1))
System.out.println (“An ArrayList is added");
List a2 = new LinkedList();
if (p1.add(a2))
System.out.println (“An LinkedList is added ");

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-4


Collections

• Here, Collections covers the Collections


Framework of the Java 2 platform.
• When you want to collect multiple objects
and retrieve them later, use a collection that
is best suited for your circumstances.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-5


Collections Framework
of the Java 2 platform
• The Java 2 platform includes a new
collections framework. A collection is an
object that represents a group of objects
(such as the familiar Vector class).
• A collections framework is a unified
architecture for representing and
manipulating collections, allowing them to
be manipulated independently of the details
of their representation.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-6
Collections Framework
of the Java 2 platform (2)
• The Collections Framework provides a
well-designed set of interfaces and classes
for storing and manipulating groups of data
as a single unit, a collection.
• The Java classes in the Collections
Framework encapsulate both the data
structures and the algorithms associated
with these abstractions

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-7


Collections Framework
of the Java 2 Platform (3)
• Interfaces: Interfaces allow collections to be
manipulated independently of the details of their
representation.
• Implementations: These are the concrete
implementations of the collection interfaces. In
essence, they are reusable data structures.
• Algorithms: These are the methods that perform
useful computations, such as searching and
sorting, on objects that implement collection
interfaces. In essence, algorithms are reusable
functionality.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-8
Interface-Based Design

interface List {…}


class LinkedList implements List {…}

List l = new LinkedList();
l.add( new Date() );
Date d = (Date)l.get(0);

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Copyright © 1998 Purple Technology,
Inc. 6-9
Overview: Core Interfaces

• Collection
• Set
• List
• Map
• SortedSet
• SortedMap

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Copyright © 1998 Purple Technology,
Inc. 6-10
Overview: Utilities
• Utility Interfaces
– Comparator
– Iterator
• Utility Classes
– Collections
– Arrays

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Copyright © 1998 Purple Technology,
Inc. 6-11
Collections and Interfaces

• Collections are primarily defined through a


set of interfaces.
• Supported by a set of classes that
implement the interfaces

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-12


Framework Interface Hierarchy

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-13


Set
• A set is just a group of unique items,
meaning that the group contains no
duplicates. The Collections Framework in
fact includes a Set interface, and a number
of concrete Set classes.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-14


Map
• A map is a special kind of set. It is a set of pairs,
each pair representing a one-directional "mapping"
from one element to another. Some examples of
maps are:
• The map of IP addresses to domain names (DNS)
• A map from keys to database records
• A dictionary (words mapped to meanings)
• The conversion from base 2 to base 10

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-15


Arrays

• Most efficient way to hold references to objects.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-16


Arrays (2)

• Advantages
– An array knows the type it holds, i.e., compile-time
type checking.
– An array knows its size, i.e., ask for the length.
– An array can hold primitive types directly.
• Disadvantages
– An array can only hold one type of objects (including
primitives).
– Arrays are fixed size.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-17


Arrays (3)

class Car{}; // minimal dummy class


Car[] cars1; // null reference
Car[] cars2 = new Car[10];
for (int i = 0; i < cars2.length; i++)
cars2[i] = new Car();
Car[] cars3 = {new Car(), new Car(), new Car()};
cars1 = {new Car(), new Car(), new Car()};
};

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-18


Linked List

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-19


Collections: Interface
public interface Collection<AnyType> {
int size( );
boolean isEmpty ( );
boolean contains (Object x );
boolean add (AnyType x );
boolean remove (Object x );
void clear ( );
...............;
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-20


public interface Collection {
// Basic Operations
int size(); Collections: Interface (2)
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element); // Optional
boolean remove(Object element); // Optional
Iterator iterator();
// Bulk Operations
boolean containsAll(Collection c);
boolean addAll(Collection c); // Optional
boolean removeAll(Collection c); // Optional
boolean retainAll(Collection c); // Optional
void clear(); // Optional
// Array Operations
Object[] toArray();
Object[] toArray(Object a[]);
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-21
The Iterator Interface

• Select each element in a collection

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-22


The Iterator Interface (2)

// the interface definition


Interface Iterator {
boolean hasNext();
Object next(); // note "one-way" traffic
void remove();
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-23


The Iterator Interface (2)

public static void main (String[] args){


ArrayList cars = new ArrayList();
for (int i = 0; i < 12; i++)
cars.add (new Car());
Iterator it = cats.iterator();
while (it.hasNext())
System.out.println ((Car)it.next());
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-24


import java.util.*; The Iterator Interface (3)
class Car{
public static void main (String[] args){
ArrayList cars = new ArrayList();
for (int i = 0; i < 12; i++)
cars.add (new Car());

Iterator it = cars.iterator();
while (it.hasNext())
System.out.println ((Car)it.next());

System.out.println ("size is " + cars.size());


cars.clear();
System.out.println ("size is " + cars.size());
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-25


UML
• In the field of software engineering, the
Unified Modeling Language (UML) is a
standardized specification language for
object modeling.
class diagram

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-26


Collection: UML Interface

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-27


Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-28
Generic Class Type
• Generic type or a parameterized type is a
class or interface type definition that has
one or more type parameters.
Example <Type> or Example<T>
• The parameter appears between the angled
brackets, <>, that follows the generic type
name (type parameter).
• The name T identifies the type parameter.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-29


Run-Time Types of Generic Type Instances
import java.util.*;
public class Example <Type> { //or Example<T>
public Example (Type item) {
System.out.println (item);
}
public Integer k;
public static void main (String [] args) {
String s = "OK"; Integer i=56; Double d =477.89;
Example <String> one1=new Example<String> (s);
Example <Integer> one2=new Example<Integer> (i);
Example <Double> one3=new Example<Double>(d);
one3.k =77;
System.out.println ("k = " + one3.k);
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-30
Integer Class

• The Integer class wraps a value of the


primitive type int in an object. An object of
type Integer contains a single field whose
type is int.
• In addition, this class provides several
methods for converting an int to a String
and a String to an int, as well as other
constants and methods useful when dealing
with an int.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-31
Integer Class (2)

public class IntegerExample {


public static void main(String[] args) {
Integer intObj1 = new Integer(10);
Integer intObj2 = new Integer("10");
System.out.println(intObj1);
System.out.println(intObj2);
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-32


Integer Class (3)

public class StringToIntegerExample {


  public static void main(String[] args) {
   
    Integer intObj1 = new Integer("100");
    System.out.println(intObj1);
   
    String str = "100";
    Integer intObj2 = Integer.valueOf(str);
    System.out.println(intObj2);
  }
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-33


Integer Class (4)
public class StringToIntegerExample {
public static void main(String[] args) {
Integer intObj1 = new Integer("100");
System.out.println(intObj1);
String str = "100";
Integer intObj2 = Integer.valueOf(str);
System.out.println(intObj2);
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-34


SimpleContainer Protocol

public interface SimpleContainer <AnyType> {


void insert( AnyType x );
void remove( AnyType x );
AnyType find( AnyType x );
boolean isEmpty ( );
void makeEmpty ( );
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-35


Multiple Type Parameters
public class Pair <KeyType, ValueType> {
public Pair (KeyType key, ValueType aValue {
key=aKey;
value =aValue;
}
......
}

Pair <String, String> entry = new Pair <String, String>


(“Fred Trhump”, “212 222 3333”);

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-36


Iterator Pattern
• Consider the problem of printing the
elements in a collection.
• Typically, the collection is an array, so
assuming that the object v is an array, its
contents are easily printed with code like
the following:
for( int i = 0; i < v. length; i++ )
System.out.println (v [i]);
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-37
Iterator Pattern (2)
• i is an iterator that controls the iteration.
• Using the integer i as an iterator, can only
store the collection in an array-like
structure.
• A more flexible alternative is to design an
iterator class that encapsulates a position
inside of a collection.
• The iterator class provides methods to step
through the collection.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-38


Iterator Pattern (3)
• If we replace:
int i
with
IteratorType ltr
then the loop is now:

for( itr = v.first(); itr.isValid( );itr.advance ( ))


System.out.printn (itr.getData( ));
• This suggests an iterator class that contains methods
such as isValid, advance, getData, and so on.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-39


Basic Iterator Design
• The first iterator design uses only three methods.
• The container class is required to provide an
iterator method. iterator returns an appropriate
iterator for the collection.
• The iterator class has only two methods:
– hasNext
– next
• hasNext returns true if the iteration has not yet
been exhausted
• next returns the next item in the collection (and in
the process. advances the current position).
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-40
package weiss.ds;
Basic Iterator Design (2)
class MyContainerIterator {
private int current = 0;
private MyContainer container;

MyContainerIterator (MyContainer c) { //constructor


container = c;
}
public boolean hasNext() {
return current <container.size;
}
public Object next() {
return container.items [current++];
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-41
Basic Iterator Design (3)

• The iterator in the MyContainerIterator


keeps a variable (current) that represents the
current position in the container, and a
reference to the container.
• The implementation of the constructor and
two methods is straightforward. The
constructor initializes the container
reference.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-42
Basic Iterator Design (4)

• The constructor initializes the container


reference.
• HasNext simply compares the curent
position with the container size.
• Next uses the current position to index the
array (and then advances the current
position).

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-43


Basic Iterator Design (5)

package weiss.ds;
public class MyContainer {
Object [] items:
int size;
public MyContainerIterator iterator ( ) {
return new MyContainerlterator( this );
}
// Other methods
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-44
Class Object java.lang.Object

• Class Object is the root of the class


hierarchy.
• Every class has Object as a superclass.
• All objects, including arrays, implement the
methods of this class.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-45


Class Object
public class RunTimeCastDemo {
public static void main(String args[]) {
Integer x = 23;
String z="35";
Object o1 = x;
Object o2 = z;
System.out.println (o1);
System.out.println (o2);
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-46


Basic Iterator Design (6)

• The iterator method in class MyContainer


simply returns a new iterator:
• Notice that the iterator must have
information about the container that it is
iterating over.
• Thus the iterator is constructed with a
reference to the MyContainer.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-47


Basic Iterator Design (7)

public static void main(String [] args) {


MyContainer v= new MyContainer ( );
v.add (“3”);
v.add (“ 2”);
System.out.println( Container contents:”);
MyContainerIterator itr = v.iterator ( );
while ( itr.hasNext ())
System.out.println( itr.next( ));
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-48
Basic Iterator Design (9)
• A limitation of this iterator design is the
relatively limited interface.
• Observe that it is impossible to reset the
iterator back to the beginning, and that the
next method couples access of an item with
advancing.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-49


MyContainer Class

package weiss.ds;
public class MyContainer {
Object[] items;
int size;
public Iterator iterator () {
return new MyContainerIterator (this);
}
// Other methods
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-50
Interface Iterator

package weiss.ds;
public interface Iterator {
boolean hasNext();
Object next();
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-51


package weiss.ds;
class MyContainerIterator implements Iterator {
private int current = 0;

MyContainerIterator
private MyContainer container;
MyContainerIterator (MyContainer c) {
container = c;
}
public boolean hasNext() {
return current < container.size;
}
public Object next() {
return container.items [current++];
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-52
Main Method
public static void main (String [] args) {
MyContainer v=new MyContainer();
v.add( “3”);
v.add (“2”);
System.out.println ("Container contents: ");
Iterator itr = v.iterator ();
while (itr.hasNext ())
System.out.println (itr.next());
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-53
The List Interface
public interface List extends Collection {
Object get (int index);
Object set (int index, Object element); // Optional
void add (int index, Object element); // Optional
Object remove (int index); // Optional
abstract boolean addAll (int index, Collection c);

int indexOf (Object o);


int lastIndexOf (Object o);

ListIterator listIterator ();


ListIterator listIterator (int index);
List subList (int from, int to);
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-54
The List Interface

• Implemented by:
– ArrayList, LinkedList, Vector

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-55


ArrayList & LinkedList Classes
• The classes ArrayList and LinkedList implement
the List interface.
• ArrayList is an array based implementation and
elements can be accessed directly via the get and
set methods.
• LinkedList is based on a double linked list
– Gives better performance on add and remove
compared to ArrayList.
– Gives poorer performance on get and set
methods compared to ArrayList.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-56


ArrayList: Example
import java.util.*;
public class Shuffle {
public static void main(String args[]) {
List l = new ArrayList();
for (int i = 0; i < args.length; i++)
l.add (args[i]);
Collections.shuffle(l, new Random());
System.out.println(l);
}
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-57


Java – Collections (Shuffle Elements)
import java.util.*;
public class ShuffleTest {
public static void main(String[] args){
List<String> sl = new ArrayList<String>();
sl.add("One"); sl.add("Two"); sl.add("Three");
sl.add("Four"); sl.add("Five"); sl.add("Six");
for(String s: sl){
System.out.println(s);
}
System.out.println();
Collections.shuffle(sl);
for(String s: sl){
System.out.println(s);
}
}
}
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-58
import java.util.*;
public class MyStack {
private LinkedList list = new LinkedList();
public void push(Object o){
list.addFirst(o);
}
public Object top(){
return list.getFirst();
}
public Object pop(){
return list.removeFirst();
}
public static void main(String args[]) {
Car myCar;
MyStack s = new MyStack();
s.push (new Car());
myCar = (Car)s.pop(); System.out.println (myCar);
}
}Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-59
List Iterator
public interface ListIterator extends Iterator {
boolean hasNext();
Object next();
boolean hasPrevious();
Object previous();
int nextIndex();
int previousIndex();
void remove(); // Optional
void set(Object o); // Optional
void add(Object o); // Optional
}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-60


Vectors

• Vectors as arrays that grow and shrink while a


program is running.
vector<String> v = new Vector<String>(20);

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-61


Vectors (2)
• To add an element
v.addElement(“Hello!);
• To get the value of an element
String temp = v.elementAt(index);
• To change the value of an existing element
v.setElementAT(“Hi, Mom!”, index);
• To learn the size of the vector
int howMany= v.size();

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-62


Vectors (3)
• To learn if the vector is empty
booleannone = v.isEmpty();
• To learn the current capacity
int howBig= v.capacity();
• To make room for more elements
v.ensureCapacity(moreElements);
• To trim to the current size
v.trimToSize();

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-63


The Map Interface

• A Map is an object that maps keys to


values. Also called an a dictionary.
• Methods for adding and deleting
– put(Object key, Object value)
– remove (Object key)
• The HashMap and HashTree classes
implement the Map interface.

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-64


The Map Interface (2)

Map myMap = new HashMap();


myMap.put ("a", "x");  // map is {a --> x}
myMap.put ("b", "y"); // map is {a-->x, b-->y}
myMap.put ("c", "x"); // map is {a-->x, b-->y, c-->x}
myMap.put ("a", "z"); // map is {a-->z, b-->y, c-->x}

Object val = myMap.get("a"); // val is "z"


myMap.remove("a"); // map is {b-->y, c-->x}

Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-65


Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-66
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-67
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-68
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-69
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-70
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-71
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-72
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-73
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-74
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-75
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-76
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-77

You might also like