Presentation is loading. Please wait.

Presentation is loading. Please wait.

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 #21 2015T1.

Similar presentations


Presentation on theme: "Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 #21 2015T1."— Presentation transcript:

1 Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 #21 2015T1

2 © Peter Andreae COMP102 21:2 Outline ArrayLists for : shorthand version of while Administration Extra Help Desk, 12-1 today. Labs: Assig 6 vs Assig 7 Terms Test #2: Next Monday, 6-7pm (7-8) for people doing PHYS114) Rooms:HM LT205, KK LT303, MC LT103 Topics: Loops, Files, Creating, defining and using Objects, Event Driven Input (GUIs), Note: Chapter 6 of textbook is on GUI's. It uses a more complex design than this course (it uses inheritance and private inner classes). Read it only if you find it helpful. Textbook: Ch 7 & 15 (but covers more than we do here)

3 © Peter Andreae COMP102 21:3 Storing lots of values In most programs you need to remember lots of values: all the flowers on the screen, so that you can make them all grow, bloom, etc all the numbers from a file, so that you can sort them all all the names and marks of students in a class, so you can update the marks and display them Can’t use lots of variables: Flower f1, f2, f3, f4, f5, f6, f7, f8, f9, … f100; int n1, n2, n3, n4, n5, … n1000; (The code would be huge!) Could use a file, but then can only read/write one at a time

4 © Peter Andreae COMP102 21:4 Arrays and ArrayLists Java has several structures that will hold lots of values: Arrays and ArrayLists: The individual places are numbered (from 0) Can refer to the places by the index Arrays: Fixed size, operations using special syntax ArrayLists: Grows as needed, all operations by method calls 12345678910110 flowers:

5 © Peter Andreae COMP102 21:5 ArrayList of Flowers flowers variable contains an ArrayList of Flower objects, flowers.get(5)is the Flower at position 5 flowers.get(i).bloom() calls bloom on the Flower at position i. (i must be less than the size of the ArrayList) flowers: 12345678910110

6 © Peter Andreae COMP102 21:6 Using ArrayList How do we create a new ArrayList? add a new value to the ArrayList? access the values in the ArrayList? change the value at an index in the ArrayList? remove a value from the ArrayList? do something to every value in the the ArrayList find out how big the ArrayList is? 01 2 3 names:

7 © Peter Andreae COMP102 21:7 Using ArrayList Creating: ArrayList names = new ArrayList (); Must specify the type of value Can’t be int or double or boolean!!! Have to use Integer or Double or Boolean (“wrapper” objects) ArrayList counts = new ArrayList (); Must have the ( ) - standard constructor, with no arguments. Type of variable Constructing the ArrayList Type of value in the ArrayList in

8 © Peter Andreae COMP102 21:8 Using ArrayList For all actions, call methods on the ArrayList: size, add, get, set, remove, clear, contains, indexOf, isEmpty, … ArrayList names = new ArrayList (); names.add(“Jim”); names.add(“Jan”); if (names.get(0).equals(“Jim”) { names.set(0, “Jane”); … names.add(1, “Bob”); names.remove(“Bob”); 01 names: “Jim” “Jan” “Bob” 2

9 © Peter Andreae COMP102 21:9 Using an ArrayList: loops Usually, want to act on lots of elements ⇒ access and assign ArrayList elements inside a loop: Print out all the names: int i= 0; while (i < names.size()) { UI.println( “Hello ”, names.get(i)); i = i +1; } Change each name to uppercase: int num= 0; while (num < names.size()) { String upName = names.get(i).toUpperCase(); names.set(num, upName); i++; } 0123 names: A B C D

10 © Peter Andreae COMP102 21:10 Using an Array : for loops Standard pattern for processing each element of an ArrayList: int i = 0 ; while (i < data.size() ){ … data.get(i) … ; i = i+1 ; } The for loop is a shorthand: for (int i = 0 ; i < data.size(); i = i+1 ) { … data.get(i) … ; } or for (int i = 0 ; i < data.size(); i++ ) { … data.get(i) … ; } Shorthand: same effect as i = i + 1; but the value is the value of i before incrementing it

11 © Peter Andreae COMP102 21:11 For loop For loop puts the intialisation  once, before the loop body is run at all condition  tested each time, before loop body run increment  run each time, after loop body run together, at the front of the loop But the meaning is (almost) exactly the same as the while loop (scope of loop variable is different) for(statement) ;;expressionstatement InitialisationConditionIncrement

12 © Peter Andreae COMP102 21:12 Using an Array: using for loops Same as before, but with for loop: ⇒ easier to read Print out all the marks: for (int num = 0 ; num < names.size(); num++) { UI.println( “Hello ” + names.get(num)); } Compute final marks from essay marks and exam marks: for (int i= 0 ; i < names.size(); i++) { names.set( i, names.get(i).toUpperCase() ); }

13 © Peter Andreae COMP102 21:13 Putting values in ArrayList ArrayList names = new ArrayList (); while (true) { String name = UI.askString(“Enter name (- to end)”); if ( name.equals(“-”) ) { break; } names.add(name); } ArrayList shipments = new ArrayList (); try { Scanner sc = new Scanner (new File(fname)); while (sc.hasNext()) { shipments.add(sc.nextDouble()); } UI.println(“read ” + shipments.size() + “ values”); } catch(…….

14 © Peter Andreae COMP102 21:14 More values in ArrayList ArrayList squares = new ArrayList (); ArrayList cubes = new ArrayList (); for (int i = 0; i < 1000; i++) { squares.add( i * i); cubes.add( i * i * i); or cubes.add(squares.get(i) * i); } for (int i = 999; i >0; i--) { UI.println( “%3d %6d %9d%n”, i, squares.get( i ), cubes.get( i) ); }

15 © Peter Andreae COMP102 21:15 Garden Program public class Garden { private ArrayList flowers = new ArrayList (); public Garden(){ UI.setMouseListener(this::doMouse); UI.addButton(“Clear”, this::doClear); UI.addButton(“Grow”, this::doGrow); UI.addButton(“Bloom”, this::doBloom); UI.addButton(“Pick”, this::doPick); } public void doMouse(String action, double x, double y){ if (action.equals(“released”)){ Flower fl = new Flower(x, y); this.flowers.add(fl); } } 01 10 30 bud 20 5 bud 2 73 49 bud

16 © Peter Andreae COMP102 21:16 Garden program Operate on the ArrayList of Flowers: private ArrayList flowers = new ArrayList (); public void doGrow(){ for (int i =0; i<this.flowers.size(); i++) { this.flowers.get( i ).grow(); } public void doBloom(){ for (int i =0; i<this.flowers.size(); i++) { this.flowers.get( i ).bloom(); } public void doBloom(){ this.flowers.clear(); UI.clearGraphics(); } 01 grow bloom pick clear 2 10 30 bud 20 5 bud 73 49 bud

17 © Peter Andreae COMP102 21:17 Garden program: Alternate design Operate on a selected Flower: private ArrayList flowers = new ArrayList (); private int selectedFlower; public void doGrow(){ this.flowers.get(this.selectedFlower ).grow(10); } public void doBloom(){ this.flowers.get(this.selectedFlower ).bloom(); } public void doDig(){ this.flowers.remove(this.selectedFlower); } 01 grow bloom pick clear 2 1 10 30 bud 20 5 bud 73 49 bud

18 © Peter Andreae COMP102 21:18 Garden program : Alternate design Operate on a selected Flower: private ArrayList flowers = new ArrayList (); private int selectedFlower; : public void doMouse(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 1 01 2

19 © Peter Andreae COMP102 21:19 Saving a Garden to a file Get file name and open file step through flowers, printing to file public void doSave(){ 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); } } 01 2 3 flowers: position(x,y) and state(height, stage): eg: 104 268 40 bud

20 © Peter Andreae COMP102 21:20 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);} } 01 2 3 flowers: 104 268 40 bud 287 132 70 bloom 524 245 20 picked 274 83 50 bud :

21 © Peter Andreae COMP102 21:21 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 01 2 3 receptionOrder: “Jim” “Ann” 4 “Cary” “Bob”

22 © Peter Andreae COMP102 21:22 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

23 © Peter Andreae COMP102 21:23 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(); }

24 © Peter Andreae COMP102 21:24 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

25 © Peter Andreae COMP102 21:25 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); }

26 © Peter Andreae COMP102 21:26 Using an Array You must not use an index that is “out of bounds” marks[-3] or marks[500] will cause an error. index must be in range 0 … length-1 If not certain, can check first: // swap values at positions n and 0 if ( 0<=n && n < marks.length ){ marks[n] = marks[0]; marks[0] = marks[n]; } double temp = marks[n]; marks[n] = marks[0]; marks[0] = temp; } 123456780 45.580.0 199 200 length 42.0... 27.013.08.511.715.0 27.017.0 n: 7 temp:


Download ppt "Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 #21 2015T1."

Similar presentations


Ads by Google