07 Implementing Collections

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 18

Implementing Collections

COMP 103 #7
Lecture Program

• Collection Interfaces and Classes


• Abstract Classes
• Type variables for defining Generic
Interfaces and Classes
• Start Implementing ArrayList

COMP103 2006/T3 2
Implementing Collections

How to implement a Collection:


1. Choose a collection Interface, or extend (specialise)
one.
2. Consider alternative data structures and algorithms
• Arrays, expanding arrays, linked lists
• Assess cost and efficiency

3. Testing

COMP103 2006/T3 3
Interfaces and Classes
• Interface • List <elemtype >
• Specifies type • Specifies sequence of elemtype
• defines method • size, get, set, add, remove,
headers only iterator, isEmpty, contains,
indexOf, add2, remove2, addAll,
addAll, clear, containsAll, equals,
hashCode, lastIndexOf,
listIterator, removeAll, retainAll,
subList, toArray.
• Class
• ArrayList<elemtype >
• implements Interface
• implements List <elemtype >
• defines fields for the
data structures to • defines array of <elemtype >
hold the data. and count
• defines method • defines constructors
bodies • defines size, add, …
• defines constructors …………
COMP103 2006/T3 4
Problem: too many methods
• There are a lot of methods in List that need to be defined in
ArrayList
• Many of them could be defined in terms of other methods
eg,
public void addAll(Collection<elemtype > other){
for (elemtype item : other)
this.add(item);
}

• Note, these definitions might not be very efficient, but they


are correct.

• Solution: An Abstract class


• “Abstract” means “Not fully defined”, and it therefore cannot
be instantiated.
• makes it easier to construct “real” classes, as some of the
work is done for us.
COMP103 2006/T3 5
Abstract Classes
• They can’t be instantiated - like an interface.
• Unlike interfaces abstract classes can contain:
• Method code, and
• Data Fields.
• Does not contain a full implementation by itself,
but enough to make it easier to write subclasses.
• That is, an abstract class provides the ‘general’ code
that all extending subclasses would share between
them.
• This code can be ‘overridden’ by new implementations
in the subclasses.
• It can have a constructor, to initialise it’s state –
but this can usually only be called by any
subclasses (protected).
• Acts 2006/T3
COMP103 as a placeholder in a class hierarchy. 6
Abstract Classes
• Delcaration:
public abstract class Employee{
private String name;
private Integer salaryStep;

protected Employee(){};
public void setName(String name){this.name = name;}
public void setSalaryStep(int step){salaryStep = step;}
…}

• Subclasses such as, manager, extend the abstract class:


• Add more data fields and methods;
• ‘finish-off’ and specialise the implementation,
• e.g: a salesperson != a manager
• (manager has ‘direct reports’, salesperson a route).
• This is a clever way to build libraries.

COMP103 2006/T3 7
Manager Example
public class Manager extends Employee{
private List<Employee> directReports;

public Manager(){…}

public addDirectReport(Employee e){


directReports.add(e);
}

public fire(Employee e){


if(directReports.contains(e)){
directReports.remove(e);
e.setSalaryStep(0);
}
}

}
COMP103 2006/T3 8
Interfaces and Classes
• Interface • List <etype >
• Specifies type
• Specifies sequence of etype
• defines method
headers • AbstractList <etype >
• Abstract Class • implements List <etype >
• implements • defines addAll, subList, …
Interface • defines add, set, get,… to be
• defines some abstract
methods
• leaves other methods • ArrayList <etype >
“abstract” • extends AbstractList
• implements fields
• Class & constructor
• extends Abstract • must implement all abstract
Class methods (add, get, …
COMP103 2006/T3 9
• defines data
List is a good example!
public interface List <E> extends Collection<E>{
public int size(); What is E?
public E get(int index);
public E set(int index, E elem); What is this
public boolean add(E elem);
a List of?
public boolean add(int index, E elem);
public E remove(int index);
public void remove(Object ob);
public Iterator<E> iterator();
E is a type variable
public void clear();
public boolean contains(Object ob);
public int indexOf(Object ob);
public boolean addAll(Collection<E> c);
:
• (Plus comments to specify the operations)
COMP103 2006/T3 10
“Generics” and Type variables
• When Declaring a variable/field holding a List:
• Must specify the type of the elements in the List
private List <Shape> drawing;

• When Constructing (Instantiating) a List object:


• Must specify the type of the elements in the List
crowd = new List <Face> ();

• When Defining the List interface, or the ArrayList class:


• We are defining every kind of List
• We use a type variable to stand for whatever
element type is specified in declaration or constructor.
public interface List <E> extends Collection <E> {

• E will be bound to a real type when a List is


declared or constructed.
COMP103 2006/T3 11
AbstractList
// Cannot construct an object of this class
public abstract class AbstractList <E> implements List<E>{
// size is declared abstract - must be defined in a real class
public abstract int size();
// isEmpty is defined in terms of size
public boolean isEmpty(){
return (size() == 0);
←Why might this be very inefficient?
}
// get is declared abstract - must be defined in a real class
public abstract E get(int index);
// contains is defined in terms of get
public boolean contains(Object ob){
for (int i = 0; i<size(); i++)
if (get(i).equals(ob) ) return true;
return false;
}
COMP103 2006/T3 12
ArrayList
public class ArrayList <E> extends AbstractList<E>{
// fields to hold the data:
need an array for the items and an int for the count.
// constructor(s)
Initialise the array
// definitions of methods not defined in AbstractList
// (other methods are inherited from AbstractList )
size()
get(index)
set(index, value)
remove(index)
add(index, value)
iterator()
// definition of the Iterator class
COMP103 2006/T3 13
Implementing ArrayList
• Data structure:
data

count

• size:
• returns the value of count

• get and set:


• check if within bounds, and
• access the appropriate value in the array

• add(index, elem):
• check if within bounds, (0..size)
• move other items up, and insert
• as long as there is room in the array !!!
COMP103 2006/T3 14
ArrayList: fields and constructor

public class ArrayList <E> extends AbstractList <E> {


private E[] data;
private int count=0;
private static int INITIALCAPACITY = 16;
/** Returns number of elements in collection as integer */
  public ArrayList(){
    data = new E [INITIALCAPACITY];
 }

// Can’t use type variables as array constructors!!!!

/** Returns number of elements in collection as integer */


  public ArrayList(){
    data = (E[]) new Object[INITIALCAPACITY];
 }

// Create as Object[ ] and cast to E[ ]

COMP103 2006/T3 15
ArrayList: size, isEmpty
public class ArrayList <E> extends AbstractList <E> {
private E[] data;
private int count=0;9
:

/** Returns number of elements in collection as integer */


  public int size () {
    return count;
 }

/** Returns true if this set contains no elements


(Overloaded). */
  public boolean isEmpty(){
    return count==0;
 } 16
COMP103 2006/T3
ArrayList: get
public class ArrayList <E> extends AbstractList <E> {
private E[] data;
private int count=0;
9

/**Returns the value at the specified index.


* Throws an IndexOutOfBoundsException is index is
out of bounds */
  public E get(int index){
    if (index < 0 || index >= count)
throw new IndexOutOfBoundsException();
    return data[index];
 }

COMP103 2006/T3 17
ArrayList: set
public class ArrayList <E> extends AbstractList <E> {
private E[] data;
private int count=0;9
:

/**Replaces the value at the specified index by the specified


value
* Returns the old value.
* Throws an IndexOutOfBoundsException if index is out of
bounds */
public E set(int index, E value){
    if (index < 0 || index >= count)
throw new IndexOutOfBoundsException();
    E ans = data[index];
    data[index] = value;
    return ans;
COMP103 18
  } 2006/T3

You might also like