Professional Documents
Culture Documents
07 Implementing Collections
07 Implementing Collections
07 Implementing Collections
COMP 103 #7
Lecture Program
COMP103 2006/T3 2
Implementing Collections
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);
}
protected Employee(){};
public void setName(String name){this.name = name;}
public void setSalaryStep(int step){salaryStep = step;}
…}
COMP103 2006/T3 7
Manager Example
public class Manager extends Employee{
private List<Employee> directReports;
public Manager(){…}
count
• size:
• returns the value of count
• 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
COMP103 2006/T3 15
ArrayList: size, isEmpty
public class ArrayList <E> extends AbstractList <E> {
private E[] data;
private int count=0;9
:
COMP103 2006/T3 17
ArrayList: set
public class ArrayList <E> extends AbstractList <E> {
private E[] data;
private int count=0;9
: