COMP 114 Chris VanderKnyff Kimberly Noonan William Luebke
What we’re going to do today… Questions from Monday’s and Wednesday’s Lecture Questions from Monday’s and Wednesday’s Lecture Example using Interfaces Example using Interfaces
Growable Array Want to be able to add Objects to the array without having to worry about if the array is large enough. Want to be able to add Objects to the array without having to worry about if the array is large enough. Want to be able to retrieve Objects out of the array. Want to be able to retrieve Objects out of the array. Want to be able to determine the number of objects we’ve added to the array. Want to be able to determine the number of objects we’ve added to the array.
Growable Array Interface public interface GrowableArray { // (?) Do you need a public here? public void add(Object o); public Object get(int i); public Object get(int i); public int size(); }
Implementation 1: Duke public class DukeProgramThatUsesArrays { public static void main(String args[]) { GrowableArray array=new DukeGrowableArray(); final int SOME_MODERATELY_SIZED_NUMBER=1000; for (int i=0;i<SOME_MODERATELY_SIZED_NUMBER;i++) { System.out.println("About to add "+i+ " to the array..."); array.add(Integer.toString(i)); System.out.println(i+" successfully “+ “added... array size is now: “+ array.size()+"."); } };
What Happened?
DukeGrowableArray public class DukeGrowableArray implements GrowableArray { private static final int MAX_SIZE=100; // (?) Why static? // (?) What's with the _'s? private Object _array[]=new Object[MAX_SIZE]; private int _size=0; public DukeGrowableArray() { } public int size() { return _size; } public Object get(int i) { return _array[i]; } public void add(Object o) { _array[_size++]=o; // (?) Order of operations! }
Implementation 2: UNC (Part 1) public class UNCGrowableArray implements GrowableArray { private static final int DEFAULT_INITIAL_SIZE=4; private Object _array[]; private int _size=0; public UNCGrowableArray() { // (?) What does the "this" do? this(DEFAULT_INITIAL_SIZE); } // (?) Why would this be useful? public UNCGrowableArray(int initialSize) { _array=new Object[initialSize]; } // MORE ON NEXT SLIDE...
Implementation 2: UNC (Part 2) public int size() { return _size; } public Object get(int i) { return _array[i]; } public void add(Object o) { if (_size==_array.length) { Object array[]=new Object[_size<<1]; // (?) Why << ? for (int i=0;i<_array.length;i++) { array[i]=_array[i]; } _array=array; } _array[_size++]=o; }
Implementation 2: UNC public class UNCProgramThatUsesArrays { public static void main(String args[]) { //GrowableArray array=new DukeGrowableArray(); GrowableArray array=new UNCGrowableArray(); final int SOME_MODERATELY_SIZED_NUMBER=1000; for (int i=0;i<SOME_MODERATELY_SIZED_NUMBER;i++) { System.out.println("About to add "+i+ " to the array..."); array.add(Integer.toString(i)); System.out.println(i+" successfully “+ “added... array size is now: “+ array.size()+"."); } };
Behold!