Java Methods Object-Oriented Programming and Data Structures 2nd AP edition with GridWorld Maria Litvin ● Gary Litvin capacity size Chapter13 java.util.ArrayList Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Objectives: • Learn about java.util.List interface • Learn about the java.util.ArrayList class, its constructors and methods • Review some of the ArrayList pitfalls • Practice with Part 4 of GridWorld ― “Critters” 13-2 java.util.ArrayList<E> • Implements a list using an array • Implements java.util.List<E> interface «interface» java.util.List java.util.ArrayList java.util.LinkedList 13-3 java.util.ArrayList<E> cont’d • Implements a list using an array. • Can only hold objects (of a specified type), not elements of primitive data types. • Keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list) capacity size "Cat" "Hat" "Bat" ... 13-4 ArrayList Generics • Starting with Java 5, ArrayList and other collection classes hold objects of a specified data type. • The elements’ data type is shown in angle brackets and becomes part of the List and ArrayList type. For example: ArrayList<String> words = new ArrayList<String>(); List<Integer> nums = new ArrayList<Integer>(); 13-5 ArrayList<E> Constructors Java docs use the letter E as the type parameter for elements in generic collections ArrayList<E> ( ) Creates an empty ArrayList<E> of default capacity (ten) ArrayList<E> (int capacity) Creates an empty ArrayList<E> of the specified capacity 13-6 ArrayList<E> Methods (a Subset) int size() boolean isEmpty () boolean add (E obj) returns true void add (int i, E obj) inserts obj as the i-th value; i must be from 0 to size() E set(int i, E obj) E get(int i) E remove(int i) boolean contains(E obj) int indexOf(E obj) i must be from 0 to size() -1 both use equals to compare objects 13-7 ArrayList Example ArrayList<String> names = new ArrayList<String>( ); names.add("Ben"); names.add("Cat"); names.add(0, "Amy"); System.out.println(names); Output [Amy, Ben, Cat] ArrayList’s toString method returns a string of all the elements, separated by commas, within [ ]. 13-8 ArrayList<E> Details • Automatically increases (doubles) the capacity when the list runs out of space (allocates a bigger array and copies all the values into it). • get(i) and set(i, obj) are efficient because an array provides random access to its elements. • Throws IndexOutOfBoundsException when i < 0 or i size() (or i > size() in add (i, obj) ) 13-9 ArrayList<E> Autoboxing • If you need to put ints or doubles into a list, use a standard Java array or convert them into Integer or Double objects • In Java 5, conversion from int to Integer and from double to Double is, in most cases, automatic (a feature known as autoboxing or autowrapping); the reverse conversion (called autounboxing) is also automatic. 13-10 ArrayList<E> Autoboxing Example ArrayList<Integer> counts = new ArrayList<Integer>( ); counts.add(17); ... int count = counts.get(0); Autoboxing: compiled as counts.add(new Integer(17)); Autounboxing: count gets the value 17 13-11 ArrayList Pitfalls // Remove all occurences // of "like" from words: int i = 0; Caution: when you remove elements, a simple for loop doesn’t work: while (i < words.size()) for (int i = 0; i < words.size(); i++) { { if ("like".equals(words.get(i)) if ("like".equals(words.get(i)) words.remove(i); words.remove(i); else } i++; } Shifts all the elements after the i-th to the left and decrements the size 13-12 “For Each” Loop • Works with List / ArrayList: ArrayList<String> words = new ArrayList<String> ( ); ... for (String word : words) { ... // process word } Basically the same as: ... for (int i = 0; i < words.size (); i++) { String word = words.get (i); ... // process word } 13-13 Lab: Index Maker fish.txt One fish Two fish Red fish Blue fish. Black fish Blue fish Old fish New fish. This one has a little star. This one has a little car. Say! What a lot of fish there are. fishIndex.txt A 12, 14, 15 ARE 16 BLACK 6 BLUE 4, 7 CAR 14 FISH 1, 2, 3, 4, 6, 7, 8, 9, 16 HAS 11, 14 LITTLE 12, 14 LOT 15 NEW 9 OF 16 OLD 8 ONE 1, 11, 14 RED 3 SAY 15 STAR 12 THERE 16 THIS 11, 14 TWO 2 WHAT 15 13-14 Index Maker (cont’d) java.util ArrayList IndexMaker extends DocumentIndex has IndexEntry Your job 13-15 GridWorld’s Critters • Described in Part 4 of the GridWorld case study • Critter is subclass of Actor • You will create subclasses of Critter • Study the examples provided with GridWorld: ChameleonCritter and CrabCritter 13-16 GridWorld’s Critters (cont’d) public void act() { if (getGrid() == null) return; ArrayList<Actor> actors = getActors( ); processActors(actors); ArrayList<Location> moveLocs = getMoveLocations( ); Location loc = selectMoveLocation(moveLocs); makeMove(loc); } • Do not override the act method in Critter’s subclasses; override other methods to achieve the desired functionality 13-17 GridWorld’s Critters (cont’d) • Pay attention to postconditions when you override Critter’s methods! ArrayList<Actor> getActors( ) The state of all actors in the grid remains unchanged. void processActors(ArrayList<Actor> actors) The state of this actor can change (except its location). The states of actors in the actors list can change. Some of the actors from the list can be removed. New actors can be added in empty grid locations. All other actors in the grid remain unchanged. 13-18 GridWorld’s Critters (cont’d) ArrayList<Location> getMoveLocations( ) The state of all actors in the grid remains unchanged. Location selectMoveLocation (ArrayList<Location> moveLocs) The state of all actors in the grid remains unchanged. void makeMove(Location loc) If loc is null, this critter is removed from the grid; otherwise this critter moves to loc. This critter’s state can change. A new actor can be added in this critter’s old location. The state of all other actors in the grid remains unchanged. 13-19 Review: • When is an ArrayList more convenient than an array? • Explain the difference between the capacity and size in an ArrayList? • What method returns the number of elements currently stored in an ArrayList? • What method is used to insert an element into an ArrayList? 13-20 Review (cont’d): • Can a double value be stored in an ArrayList<Double>? • What is autoboxing? • Can a “for each” loop be used with ArrayLists? • Can a class extend ArrayList<String>? • Can an object change after it has been added to an ArrayList? 13-21 Review (cont’d): • Name the three Critter’s methods that cannot change the state of any actor in the grid. • Which Critter’s methods are allowed to add new actors to the grid? • Which Critter’s methods are allowed to change the location of this critter? 13-22