Presentation is loading. Please wait.

Presentation is loading. Please wait.

IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()

Similar presentations


Presentation on theme: "IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()"— Presentation transcript:

1 IMPLEMENTING ARRAYLIST – Part 2 COMP 103

2 RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set() and remove() TODAY  ArrayList: add(), ensuring capacity, iterator for ArrayList 2 RECAP-TODAY

3 ArrayList: add (pseudocode) public class ArrayList extends AbstractList { 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 // increment the ‘count’ variable } 9 3

4 ArrayList: add public class ArrayList extends AbstractList { private E[] data; private int count=0; : /** Adds the specified element at the specified index */ public void add(int index, E item){ if (index = count) ←check sensible throw new IndexOutOfBoundsException(); for (int i=count; i > index; i--) ←move items up data[i]=data[i-1]; data[index]=item; ←insert count++; ←increment }  What’s wrong ??? (two things) 9 4

5 ArrayList: add (fixed) public class ArrayList extends AbstractList { private E[] data; private int count=0; : /** Adds the specified element at the specified index.*/ public void add(int index, E item){ if (index count) ←can add at end! throw new IndexOutOfBoundsException(); ensureCapacity();←make room for (int i=count; i > index; i--) data[i]=data[i-1]; data[index]=item; count++; } 9 5

6 Increasing Capacity  three steps: 8 data count newArray data.length = 8 6 ArrayList

7 ArrayList: ensureCapacity /**Ensure 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 } 7 1 ? INITIALCAPACITY ? data.length ? How much bigger should this new array be?

8 ArrayList: What else ?  iterator():  defining an iterator for ArrayList.  Cost:  What is the cost (time) of adding or removing an item ?  How expensive is it to increase the size ?  How should we increase the size ? 8

9 An iterator for ArrayList 9 List toDoList = new ArrayList (); iter toDoList 0 1 2 3 4 Iterator iter = toDoList.iterator(); Conforms to the interface Iterator so… has these methods: hasNext() next() remove() Conforms to the interface List so… has these methods: add() remove() contains(), iterator(), etc… etc...

10 Iterator 10 list nextIndex 0 9 ArrayList: Iterator:

11 ArrayList: iterator 11 /** Returns an iterator over the elements in the List */ public Iterator iterator() { return new ArrayListIterator (this); } /** Definition of the iterator for an ArrayList */ private class ArrayListIterator implements Iterator { // fields to store state // constructor // hasNext(), // next(), // remove() } Technical point: - in general, an iterator will need to know the object it is attached to. But in our case it isn’t strictly necessary to pass it in (as “this”), because we’re going to put the iterator in as a “private inner class” of ArrayList.

12 ArrayList iterator 12 private class ArrayListIterator implements Iterator { private ArrayList list; // reference to the list object private int nextIndex; // the index of the next value to return private boolean canRemove = false; // to allow the “remove” operation /** Constructor */ private ArrayListIterator (ArrayList list) { this.list = list; nextIndex = 0; } /** Return true if the array has at least one more element */ public boolean hasNext () { return (nextIndex < list.count); }

13 Iterator: next, remove (simple version) 13 /** Return next element in the List */ public E next () { if (nextIndex >= list.count) throw new NoSuchElementException(); E temp = list.get(nextIndex); nextIndex++; return temp; ← increment and return } /** Should remove from the list the last element that was returned by the iterator. */ public void remove(){ throw new UnsupportedOperationException(); } Notice: this means “remove()” should only be called once, per call to “next()” !

14 Example 14 0123456789 9 list nextIndex 5 canRemove true

15 Iterator: next, remove (smarter version) 15 /** Return next element in the List */ public E next () { if (nextIndex >= list.count) throw new NoSuchElementException(); canRemove = true; ← for the remove method E temp = list.get(nextIndex); nextIndex++; return temp; } /** Remove from the list the last element returned by the iterator. * Can only be called once per call to next. */ public void remove(){ if ( ! canRemove ) throw new IllegalStateException(); canRemove = false;← can only remove once nextIndex--; ← put counter back to last item list.remove(nextIndex); ← remove last item }

16 Multiple Iterators 16 list nextIndex 3 canRemove true list nextIndex 5 canRemove true 0123456789 9

17 Iterator: Summary  Each iterator keeps track of its own position in the List  Removing the last item returned is possible, but… ...The implementation is not smart, and may be corrupted if any changes are made to the ArrayList that it is iterating down.  How to modify this to use something other than a boolean field to make it possible to work more generally? (Hint: java.util.ArrayList uses a counter!)  Note that because it is an inner class, it has access to the ArrayList's private fields. 17

18 Analysing Costs (in general) How can we determine the costs of a program?  Time:  Run the program and count the milliseconds/minutes/days.  Count number of steps/operations the algorithm will take.  Space:  Measure the amount of memory the program occupies.  Count the number of elementary data items the algorithm stores.  Programs or Algorithms?  Both programs: benchmarking algorithms: analysis 18

19 ArrayList: Cost  What’s the cost of contains, get, set, remove, add…?  How should we implement ensureCapacity() ?  How do you measure cost of operations on collections?  What is “cost” of an algorithm?  Number of steps required if the list contains n items:  get:  set:  remove:  add: 19


Download ppt "IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()"

Similar presentations


Ads by Google