Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays COMP 102 # T1
© Peter Andreae COMP :2 Menu Nulls in an array ArrayLists: like an array whose size can change. Administration: Terms Test #2: Next Monday, 5-6pm (6-7 for people doing PHYS114) Rooms:HM LT205, KK LT303, MC LT103 Topics: Loops, Files, Creating, defining and using Objects, Event Driven Input (GUIs),
© Peter Andreae COMP :3 Arrays with a null What happens if we put a null into the array of flowers? flowers[4] = null; How do we draw all the flowers now? public void redraw(){ for(int i = 0; i < this.flowers.length; i++) { if (this.flowers[ i ] != null) { this.flowers[ i ].draw(); } } } length: 12 flowers: null If the value might be null, MUST check before calling methods on it Causes NullPointerException when i gets to 4 !!!
© Peter Andreae COMP :4 Arrays and ArrayLists Arrays have a fixed size Size is determined when array is created You cannot make it larger (or smaller) You need to know how large it should be at creation. What if the program must read and store values from a file of an unknown size? examdata.txt did not specify how many lines there would be! allows the user to keep adding values to the array? Garden allowed the user to add flowers for ever! has to remove values? If flowers can be dug up… ArrayLists are lists of values that can grow and shrink.
© Peter Andreae COMP :5 Arrays vs ArrayLists Arrays are built-in to Java. Arrays are objects Special square brackets syntax for declaring, creating, and accessing String[ ] names; new String[ 20 ]; names[ id ] = names[ id-1] + “-senior”; ArrayList is a class in the standard libraries ArrayLists are objects Equivalent to an array that changes its size as needed, No bracket syntax Just ordinary constructors and methods Requires additional type syntax - angle brackets.
© Peter Andreae COMP :6 Using ArrayList Creating: ArrayList names = new ArrayList (); Using: For all actions, call methods on the ArrayList: size, add, get, set, remove, clear, contains, indexOf, isEmpty, … eg: names.set(0, (names.get(1) + names.get(names.size()-1))); contrast: names[0] = names[1] + names[names.length-1]; eg: To do something on each value in an ArrayList: for (int i =0; i<names.size(); i++) { UI.println(names.get( i )) } Type of variable Constructing the ArrayList Type of value in the ArrayList in
© Peter Andreae COMP :7 Garden program Make an ArrayList of to hold Flowers: private ArrayList flowers = new ArrayList (); Garden: initially, have no flowers when click on canvas, add a flower when click on grow/bloom/pick, do something to every flower when click on clear remove all flowers grow bloom pick dig 01 2
© Peter Andreae COMP :8 Garden program Make an ArrayList of Flowers: private ArrayList flowers = new ArrayList (); Add to the ArrayList of Flowers public void mousePerformed(String action, double x, double y){ if (action.equals(“released”)){ Flower fl = new Flower(x, y); this.flowers.add(fl); } } grow bloom pick dig Puts value at the end of the list. 01 2
© Peter Andreae COMP :9 Garden program Operate on the ArrayList of Flowers: private ArrayList flowers = new ArrayList (); public void buttonPerformed(String button){ if (button.equals(“grow”)){ for (int i =0; i<this.flowers.size(); i++) { this.flowers.get( i ).grow(10); } } else if (button.equals(“bloom”)){ for (int i =0; i<this.flowers.size(); i++) { this.flowers.get( i ).bloom(); } } else if (button.equals(“pick”)){ … } else if (button.equals(“clear”)){ this.flowers.clear(); } 01 grow bloom pick clear 2
© Peter Andreae COMP :10 Garden program: Alternate design Operate on a selected Flower: private ArrayList flowers = new ArrayList (); private int selectedFlower; public void buttonPerformed(String button){ if (button.equals(“grow”)){ this.flowers.get(this.selectedFlower ).grow(10); } else if (button.equals(“bloom”)){ this.flowers.get(this.selectedFlower ).bloom(); } else if (button.equals(“pick”)){ this.flowers.get(this.selectedFlower ).pick(); … } else if (button.equals(“dig”)){ this.flowers.remove(this.selectedFlower); } 01 grow bloom pick clear 2 1
© Peter Andreae COMP :11 Garden program : Alternate design Operate on a selected Flower: private ArrayList flowers = new ArrayList (); private int selectedFlower; : public void mousePerformed(String action, double x, double y){ if (action.equals(“released”)){ for (int i =0; i<this.flowers.size(); i++) { if (this.flowers.get( i ).touching(x, y) ) { this.selectedFlower = i ; return ; } } // if not touching a flower, plant one this.flowers.add(new Flower(x, y)); } grow bloom pick dig 01 2
© Peter Andreae COMP :12 Saving a Garden to a file Get file name and open file step through flowers, printing to file public void save(){ File saveFile = new File(UIFileChooser.save("File for Garden")); try{ PrintStream out = new PrintStream(saveFile); for (int i =0; i<this.flowers.size(); i++) { out.println(this.flowers.get(i).toString()); } out.close(); } catch(IOException e) { UI.println("File saving failed: "+e); } } flowers: position(x,y) and state(height, stage): eg: bud
© Peter Andreae COMP :13 Loading Garden from a file Get file name and open file Step through file, reading public void load(){ try { this.flowers = new ArrayList (); // or this.flowers.clear(); File file = new File(UIFileChooser.open("Choose Garden File")); Scanner sc = new Scanner(file); while (sc.hasNext()){ Flower fl= new Flower(sc.nextDouble(), sc.nextDouble(), sc.nextDouble(), sc.next () ); this.flowers.add(fl); } sc.close(); } catch(IOException e){UI.println("File loading failed: "+e);} } flowers: bud bloom picked bud :
© Peter Andreae COMP :14 Methods on ArrayList mylist.size() returns the number of items in mylist. Note contrast to array:.size() vs.length UI.printf(“The garden had %d flowers%n”, flowers.size()); mylist.add(item) adds the item at the end of the ArrayList balloons.add( new Balloon(x, y, color) ); mylist.add(index, item) inserts the item at position index ( 0.. size ) int pos = UI.askInt(“Where do you want ” +name); receptionOrder.add(pos, name); item must be of the right type receptionOrder: “Jim” “Ann” 4 “Cary” “Bob”
© Peter Andreae COMP :15 if (first>=0 && first =0 && scnd<attackList.size() && first!=second){ Methods on ArrayList mylist.get(index) returns the item at position index (0.. size-1) equivalent to myArray[index] mylist.set(index, item) replaces the current value at position index with item returns the old value at index equivalent to myArray[index] = item index must be 0.. size-1 UI.print(“Which two units do you want to swap?”); int first = UI.nextInt(); int scnd = UI.nextInt(); String temp = attackList.get(first); attackList.set(first, attackList.get(scnd)); attackList.set(scnd, temp); attackList.set(first, attackList.set(scnd, attackList.get(first))); Or
© Peter Andreae COMP :16 More Actions on ArrayList mylist.isEmpty() returns true iff there are no items in mylist. // Make each unit advance, if there are any units if ( ! attackList.isEmpty() ) { for ( int i=0; i<attackList.size(); i++ ) { Unit unit = attackList.get(i); unit.checkPath(); unit.advance(3); } } mylist.clear() removes all values from the list. // Restart and clear the list of all elements. if ( button.equals(“Restart” )) { UI.clearGraphics(); flowers.clear(); }
© Peter Andreae COMP :17 More Actions on ArrayList mylist.contains(item) returns true iff the item is somewhere in mylist mylist.remove(item) removes the item, if it is present returns true iff item was removed // Respond to a “Remove Person” button String name = UI.askString(“Person to remove”); if (receptionOrder.contains(name)){ receptionOrder.remove(name); } else { UI.println(“That person is not in the reception order”); } if ( ! receptionOrder.remove(name) ){ UI.println(“That person is not in the reception order”); } first occurrence of item if item is at several places in the list Or
© Peter Andreae COMP :18 More Actions on ArrayList mylist.indexOf(item) returns the position of item in mylist returns -1 if the item is not present // Report position on waiting list String name = UI.askString(“Your name:”); UI.printf(“You are number %d in order%n”, waitingList.indexOf(name)) mylist.remove(index) removes the item at position index (0.. size-1) returns the value that was removed // Remove every third unit from attackList for (int index=1; index<attackList.size(); index = index+3){ attackList.remove(index); }
© Peter Andreae COMP :19 ArrayLists of numbers/booleans ArrayLists can only hold objects! ArrayList myNums; ArrayList sizes = new ArrayList (); How do we store a list of numbers? (or boolean values)? Have to use “wrapper” classes to wrap up the numbers into objects. Double, Integer, Boolean Java will automatically wrap and unwrap them as needed. ArrayList myNums; ArrayList ageList = new ArrayList (); for (int age = 18; age <= 45; age++){ ageList.add(age) } double, int, long, float, boolean, etc are primitive values, not objects.
© Peter Andreae COMP :20 Using ArrayLists of numbers public void analyseNumbers(String fileName){ ArrayList nums = new ArrayList (); try { Scanner sc = new Scanner(new File(fileName)) while (sc.hasNextDouble()){ nums.add(sc.nextDouble()); } sc.close(); } catch(IOException e){UI.println(“Reading numbers failed: "+e);} double max = Double.NEGATIVE_INFINITY; for (int i=0; i<nums.size(); i++ ) { double num = nums.get(i); if ( num > max) { max = num; } UI.printf(“%.3f is the largest of %d numbers%n”, max, nums.size()); } Read numbers into ArrayList Step through numbers to find largest
© Peter Andreae COMP :21 Arrays vs ArrayList Use an array if it will never change size, and you know how big it will need to be at the point you need to create it. Use an ArrayList if the size will change, or you don’t know how big it will need to be. Arrays have convenient syntax [ ] ArrayLists have convenient methods.