Presentation is loading. Please wait.

Presentation is loading. Please wait.

Implementing ArrayList Part 1

Similar presentations


Presentation on theme: "Implementing ArrayList Part 1"— Presentation transcript:

1 Implementing ArrayList Part 1
COMP 103 Implementing ArrayList Part 1 Thomas Kuehne, Marcus Frean, Rashina Hoda, and Peter Andreae Thomas Kuehne School of Engineering and Computer Science, Victoria University of Wellington 2016-T2 Lecture 6

2 RECAP-TODAY RECAP In the last lectures we looked at
2 RECAP In the last lectures we looked at Lists, Queues, Stacks Sets, Maps TODAY We will implement ArrayList from scratch to gain a deeper understanding of ArrayList make a first foray into complexity analysis learn how to implement a Java Collections Library interface

3 extends implements “extends” implies subtyping; instances of subtypes will behave like their supertypes expect them to “implements” signifies realisation; classes promise to fulfill the contracts defined by (interface) types

4 Inheritance ("extends")
4 public class Square extends Shape {...} public class Dictionary extends Book { ... } public interface List <E> extends Collection <E> { ... } Java uses the reserved word extends to indicate that a class or interface is being derived from an existing one. Extends establishes a subtype relationship. every Dictionary is a (behaves like a) Book every List is a (behaves like a) Collection To support this, all methods defined in the parent class (and all its variables, if any) are inherited. More on this in SWEN221…

5 Interfaces and Classes
5 Interface Specifies type (typically) defines method signatures only Class Implements interface defines variables for the data defines method bodies defines constructors List <E> Specifies sequence of E size, add, get, set, remove, addAll, clear, contains, containsAll, equals, hashCode, isEmpty, indexOf, lastIndexOf, iterator, listIterator, … ArrayList <E> implements List <E> defines array of <E> defines size, add, … defines constructors

6 Defining ArrayList Design the data structures to store the elements
6 Design the data structures to store the elements array of items count Define the fields and constructors public class ArrayList <E> implements List<E> { private E [ ] data; private int count; Define all the methods specified in the List interface: size() add(E o) add(int index, E element) contains(Object o) get(int index) isEmpty() clear() set(int index, E element) indexOf(Object o) remove(int index) remove(Object o) lastIndexOf(Object o) iterator() equals(Object o) hashCode() listIterator() listIterator(int index)

7 Implementing ArrayList
7 Data structure: data count size() returns the value of count get(index) and set(index, elem) check if index is within bounds, and access/set the appropriate slot in the array add (index, elem) check if index is within bounds, (0..size) (move other items up, and) insert element ensure further capacity if the currently used array becomes too small

8 ArrayList: fields and constructor
8 public class ArrayList <E> implements List <E> { private E[ ] data; private int count=0; private static final int INITIALCAPACITY = 16; . We could do this, but it would imply a lot of work!

9 ArrayList: fields and constructor
9 public class ArrayList <E> extends AbstractList <E> { private E[ ] data; private int count=0; private static final int INITIALCAPACITY = 16; public ArrayList() {     data = new E [INITIALCAPACITY];  } We cannot use type variables as array constructors! Have to create as Object[ ], and then cast to E[ ] Compiler will warn, but the warning is safe to ignore here may use This saves us considerable effort and will be explained in the next lecture Cannot use “E[]” because of “type erasure”. (E[ ]) new Object[INITIALCAPACITY];

10 ArrayList: size(), isEmpty()
10 public class ArrayList <E> extends AbstractList <E> { private E[ ] data; private int count=0; : number of elements in collection as integer */   public int size () {     return count;   } true, if this set contains no elements. */   public boolean isEmpty() {     return count==0;   } 9

11 ArrayList: get(index)
11 public class ArrayList <E> extends AbstractList<E> { private E[ ] data; private int count=0; : the element at the specified index. * Throws an IndexOutOfBoundsException, if index is out of bounds*/   public E get(int index) {     if (index < 0 || index >= count) throw new IndexOutOfBoundsException();     return data[index];   }  9

12 ArrayList: set(index, element)
12 public class ArrayList <E> extends AbstractList<E> { private E[ ] data; private int count=0; : /** Replaces the element at the specified index by the specified element. the old element. * Throws an IndexOutOfBoundsException, if index is out of bounds */ public E set(int index, E element) {     if (index < 0 || index >= count) throw new IndexOutOfBoundsException();     E oldElement = data[index];     data[index] = element;     return oldElement; } 9

13 ArrayList: remove(index)
13 public class ArrayList <E> extends AbstractList <E> { private E[] data; private int count=0; /** Removes the element at the specified index, and returns it. * Throws an IndexOutOfBoundsException if index is out of bounds */ public E remove (int index) {     if (index < 0 || index >= count) throw new IndexOutOfBoundsException();     E oldElement = data[index]; ← remember old element     for (int i=index; i < count-1; i++) ← move items down       data[i]=data[i+1];            count--; ← adjust size variable data[count] = null; ← delete reference     return oldElement; ( garbage collection) }   9 The last assignment in the for loop goes out of bounds It leaves a copy of the last item just beyond the end of the “real” items, which may prevent garbage collection.

14 ArrayList: add (pseudocode)
14 public class ArrayList <E> extends AbstractList <E> { private E[] data; private int count=0; : // Adds the specified element at the specified index public void add(int index, E item) { // check that the index is within the allowed bounds // above the index, move the items up, starting at the last // insert the item into the gap  // adjust the size variable }   9 This won’t let you add an item at the end!! What happens if the array is full?

15 ArrayList: add What’s wrong??? (two issues)
15 public class ArrayList <E> extends AbstractList <E> { private E[] data; private int count=0; : // Adds the specified element at the specified index public void add(int index, E item) {   if (index < 0 || index count) throw new IndexOutOfBoundsException();   for (int i=count; i > index; i--) ← move items up     data[i] = data[i-1];   data[index] = item; ← insert element   count++; ← adjust size variable }   What’s wrong??? (two issues) 9 This won’t let you add an item at the end!! What happens if the array is full? >= > ← can add at end! ensureCapacity(); ← make room, if required

16 Ensuring Capacity Three steps: ArrayList data.length = 8 data count 16
newArray

17 ArrayList: ensureCapacity
17 /** * Ensures data array has sufficient number of elements * to add a new element */ private void ensureCapacity () {   if (count < data.length) return; ← there is room already   E [ ] newArray = (E[ ]) (new Object[data.length + …....] );    for (int i = 0; i < count; i++) ← copy to the new array     newArray[i] = data[i];   data = newArray; ← replace old array with new one } How much bigger should this new array be? One ? INITIALCAPACITY ? data.length ?


Download ppt "Implementing ArrayList Part 1"

Similar presentations


Ads by Google