Title: Chapter 13 Implementing lists: array implementations
1Chapter 13 Implementing lists array
implementations
2Objectives
- After studying this chapter you should understand
the following - the idea of an array and array index
- list implementations using arrays and the Vector
class - shallow and deep copies
- the method clone and the interface Cloneable.
3Objectives
- Also, you should be able to
- define array variables, create arrays, and access
array components - write algorithms having arrays as parameters
- define classes whose components include array
instances.
4Anatomy of an array
- a contiguous sequence of variables.
- all of the same type.
- Each variable is identified by its index.
- Index values are integers.
- Index of first entry is 0.
5Arrays
- Type of array element
- primitive type (char, int, boolean, double,
etc.) - or
- reference type (Student, PlayingCard, Object,
etc.) - Length of array number of component variables
- If length of array is n, index range from 0 to
n-1. - length of array is fixed after creation.
- Access of an array variable is in constant time
6Arrays
- They are subclass of Object.
- Have a public final int component length.
- int denotes the class array-of-int,
- Student denotes the class array-of-Student.
7Defining arrays
int grades
- Creates an array-of-int named grades
- Creates an array-of-Student named cs2125.
Student cs2125
- Note declaring the variable does not create an
array.
8Defining arrays
grades new int5 cs2125 new Student5
- create two arrays of length 5, and
- assign references to specified variables
int
cs2125
0
0
grades
1
0
2
0
3
0
4
0
5
length
9Accessing array components
grades3
- is an int variable We can also write
grades3 100 grades4 grades3/2
10Accessing array components
cs21250 new Student() cs21250.payFees(100)
- Important index value used to access an array
variable must be in range 0 to length of array - 1
11Initializing array variables
- Can assign each component of array grades 100 via
for (int i 0 i lt grades.length i
i1) gradesi 100
12ArrayIndexOutOfBoundsException
- A negative index or greater than or equal to
array length results in a run-time
errorArrayIndexOutOfBoundsException.
for (int i 0 i lt grades.length i
i1) gradesi 100
- Stores value 100 in all components of array
grades, but fails on last iteration when i equals
grades.length with error - ArrayIndexOutOfBoundsException
13Implementing List using an array
- Allocate array to hold references to elements of
list. - array is a list component containing the list
elements. - Array component 0 references first element of
list, component 1 references the second, and so
on. - Length of list is bounded by length of array, and
array length is fixed when the array is created.
14Implementing List using an array
- Call list implementation class using an array
BoundedListltElementgt - Require that a maximum list size be specified
when an instance is created.
15BoundedListltElementgt and ListltElementgt
- Problem ListltElementgt interface does not put a
requirement on the size of lists. - BoundedListltElementgt must place a requirement in
its add methods - list size be less than its maximum for add to
occur. - Preconditions for BoundedList add are stronger
than the preconditions for List add. - BoundedList should not be a subtype of List.
- Implement BoundedList as an independent class.
16BoundedList constructor
public class BoundedListltElementgt A list of
Elements with a fixed maximum size. public
BoundedList (int maxSize) Create a new
BoundedList with a specified maximum
size. require maxSize gt 0 ensure isEmpty(
new BoundedList(n))
- Ensure guarantees to create an empty list.
- The implementation array size is maxSize.
- Naming BoundedLists array component elements
- elements.length maxSize
17BoundedList data components
- Data components
- array containing the elements,
- an int variable containing list length.
-
18BoundedList data components
- Not legal to define an array using the type
parameter, Element, to specify type of array
entries. - For arrays must use Object as type of its entries.
private Object elements // elements of the
list private int size //
size of the list
19Constructor implementation
public BoundedList (int maxSize) assert
maxSize gt 0 elements new ObjectmaxSize si
ze 0
BoundedListltStudentgt roll new
BoundedListltStudentgt(5)
20add(int I, Element elm) implementation
- add(int,Element) shuffles portion of the array
down. - Example list contains six elements, and a new
element is to be inserted at index position 2. - Entries at indices 2,3,4,5 must be moved down,
starting with the last, to make room for new
element.
21remove(int index) implementation
- remove(int) shuffles portion of the array up.
- Example list contains six elements, and must
remove element at index position 2 - entries at indices 2,3,4,5 must be moved up,
starting with the the one at index 3.
22BoundedList implementation
public Element get (int index) assert 0 lt
index index lt size return (Element)elementsi
ndex public int indexOf (Element element)
int i 0 while (i lt size
!element.equals(elementsi) i i1 if (i lt
size) return i else return -1
23BoundedList implementation
public void add (Element element) assert size
lt elements.length elementssize
element size size1 public void add (int
index, Element element) assert 0 lt index
index lt size assert size lt elements.length fo
r (int i size-1 i gt index i
i-1) elementsi1 elementsi elementsinde
x element size size1
24BoundedList implementation
public void set (int index, Element element)
assert 0 lt index index lt
size elementsindex element public void
remove (int index) assert 0 lt index index
lt size for (int i index i lt size-1 i
i1) elementsi elementsi1 size
size-1
25Copies and Clones
- For objects with lists as components values,
provide a query that returns a copy of the list
component rather than list itself.
26Copies and Clones
- shallow copy list is copied, but not its
elements.
public BoundedListltElementgt copy ()
BoundedListltElementgt theCopy new
BoundedListltElementgt(this.elements.length) theCo
py.size this.size for (int i 0 i lt
this.size i i1) theCopy.elementsi
this.elementsi return theCopy
27A shallow copy of a list ref entries are copied.
Object
0
BoundedList
this
1
2
elements
3
??
3
Student
size
4
??
5
length
Student
Object
0
Student
BoundedList
theCopy
1
2
elements
3
3
size
4
5
length
28A deep copy of a list components are copied.
Object
Student
a
0
1
Student
b
2
elements
3
??
3
size
4
??
Student
c
5
length
Object
Student
aCopy
0
BoundedList
theCopy
1
Student
bCopy
2
elements
3
3
size
4
Student
cCopy
5
length
29clone method
- The class Object defines a method clone specified
as - protected Object clone ()
- throws CloneNotSupportedException
- Create a copy of this Object.
- throws CloneNotSupportedException means method
may fail during execution
30clone method
- Objects clone produces a very shallow copy of
the Object all instance variable values are
copied.
31Relationship between an object and its clone
- If obj is an object
- obj ! obj.clone()
- obj.equals(obj.clone())
- obj instanceof someType if and only
if obj.clone() instanceof someType - Since clone returns an Object, you must cast
result
Date date1 new Date() Date date2
(Date)date1.clone()
32Cloneable interface
public interface Cloneable
- Its an interface with no methods.
- Implemented by any class that supports (or
overrides) clone. - clone checks to see if object is an instance of a
class implementing Cloneable. - If so, makes shallow copy of object.
- Otherwise, fails with CloneNotSupportedException.
33BoundedList copy
- We choose not to define BoundedList to implement
Cloneable - If we do, clone() forces us to define equals() in
BoundedList. - BoundedList is a mutable class, with no immutable
set of properties to define equals() - We provide our own copy algorithm.
34Advantages and limitation of array implementations
- List elements can be accessed in constant time
- get(int),
- add(Element),
- set(int,Element).
- The following operations are linear
- remove(int),
- add(int,Element),
- indexOf(Element)
35Advantages and limitation of array implementations
- Number of steps required (for add, remove)
increases in proportion to size of list. - On average, half the list must be shifted up or
down to add or remove. - client must have a good idea of the ultimate size
of a list - Choosing a size that is too large will waste
space - choosing a size too small will cause the program
to fail.
36Dynamic lists
- Two types of list implementations
- Bounded set a maximum list size,
- Dynamic no list size upper bound.
37Dynamic lists
- To implement a dynamic list solution using
arrays, which have fixed size, create a larger
array when necessary.
private void makeRoom () if (this.size
elements.length) // need a bigger array, so
make one twice as big Object newArray new
Object2elements.length // copy contents of
old array to new for (int i 0 i lt
elements.length i i1) newArrayi
elementsi elements newArray // replace
old array with new
38Dynamic list
- The add(Element) method invokes make room
public void add (Element element)
makeRoom() elementssize element size
size1
- Disadvantage add operation can be expensive.
39Implementing a Dynamic list DefaultList
- java.util.VectorltElementgt
- contains an Object array.
- Vector add() replaces array with larger one
when needed. - java.util.VectorltElementgt
- provides the List functionality required.
- But Vector interface is different to List
interface.
40Implementing a Dynamic list DefaultList
- adapt (wrap) Vector
- DefaultList Implementation has Vector component
- DefaultList will extend AbstractList.
41Static diagram for DefaultList
interface
ListltElementgt
adaptee
42DefaultList implementation
public class DefaultListltElementgt extends
AbstractListltElementgt private
java.util.VectorltElementgt elements public
DefaultList () this.elements new
java.util.vectorltElementgt() public int size
() return this.elements.size() public
Element get (int index) return
this.elements.get(index)
43DefaultList implementation
public void add (int index, Element
element) this.elements.add(index,element)
public void remove (int index)
this.elements.removeElementAt(index) pub
lic void set (int index, Element element)
this.elements.setElementAt(element,index)
44DefaultList implementation
public DefaultListltElementgt copy ()
DefaultListltElementgt copy new
DefaultListltElementgt() int i 0 while (i lt
this.size()) copy.add(this.get(i)) i
i1 return copy //end of DefaultList
45Summary
- Examined Javas array classes.
- An array is a primitive structure that consists
of a contiguous sequence of variables, all of the
same type. - Array component can be a primitive type or a
reference type. - Access to an array element requires only constant
time, independent of the size of the array. - Array constructor requires integer specifying
size of array. - Array size is fixed once the array is created.
46Summary
- Used Object arrays to implement a variation of
the interface ListltElementgt BoundedListltElementgt.
- The array is used to store the elements of the
list. - Methods get(int), set(int,Element), and
add(Element) require constant time to execute. - Methods add(int,Element) and remove(int), are
linear. - Number of steps required, on average, increases
in proportion to the size of the list.
47Summary
- Considered several variations of copy method.
- Shallow copy copies instance variable values
from the original object to the copy. - If an object references another component object
by means of an instance variable, both the object
and its copy will reference the same component
object. - Deep copy copies the component objects rather
than just reference values.
48Summary
- Considered Object method clone and how a class
turns on the cloning facility by implementing
the interface Cloneable. - Method clone should produce a different object
equal to, and of same class as, the cloned object.
49Summary
- Considered an approach to solve the fixed size
limitation of BoundedListltElementgt. - create a new, larger array to hold list elements
when the existing array is filled. - The Java class java.util.VectorltElementgt used to
build DefaultListltElementgt takes this approach. - Elements are stored in an array. When an element
is added to the Vector and there is no room in
the array, a new, larger array is created.
Elements are copied from the old array to the new.