Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Arrays COMP 102.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Chapter 7 – Arrays.
Array Lists Chapter 7.2 Pages Array Lists In Java, Arrays are an important structure for storing data. We will learn more about arrays later,
Programming with Collections Collections in Java Using Arrays Week 9.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Java Arrays and ArrayLists.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Interfaces.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Interfaces.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington “For each” & Patterns with.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input TextFields,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Classes, Objects, Fields,
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Fields, Constructors.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Loops and Input COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Event-driven Input COMP 102.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
The ArrayList Data Structure The Most Important Things to Review.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
The ArrayList Data Structure Standard Arrays at High Speed!
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] : double[] data = new double[10]; When array.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on ArrayLists COMP 102.
Chapter 9 Introduction to Arrays Fundamentals of Java.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
More on Arrays Review of Arrays of ints, doubles, chars
Chapter VII: Arrays.
Chapter 7 – Arrays and Array Lists
(like an array on steroids)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
ArrayLists.
ArrayLists 22-Feb-19.
ArrayLists 27-Apr-19.
Review: libraries and packages
Presentation transcript:

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.