Second AP* Edition — with GridWorld

Java Methods
Object-Oriented Programming and Data Structures
Maria Litvin
Phillips Academy, Andover, Massachusetts

Gary Litvin
Skylight Software, Inc.

Skylight Publishing Andover, Massachusetts

Skylight Publishing 9 Bartlet Street, Suite 70 Andover, MA 01810 web: e-mail:

Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the authors and Skylight Publishing.

Library of Congress Control Number: 2010915303 ISBN 978-0-9824775-7-1
* AP and Advanced Placement are registered trademarks of The College Board, which was not involved in the production of and does not endorse this book.

The names of commercially available software and products mentioned in this book are used for identification purposes only and may be trademarks or registered trademarks owned by corporations and other commercial entities. Skylight Publishing and the authors have no affiliation with and disclaim any sponsorship or endorsement by any of these product manufacturers or trademark owners. Oracle, Java, and Java logos are trademarks or registered trademarks of Oracle Corporation and/or its affiliates in the U.S. and other countries. SCRABBLE® is the registered trademark of HASBRO in the United States and Canada and of J.W. Spear and Sons, PLC, a subsidiary of Mattel, Inc., outside the United States and Canada.

1 2 3 4 5 6 7 8 9 10

16 15 14 13 12 11

Printed in the United States of America

1 13.4 13.7 362 ArrayList’s Structure 362 ArrayList’s Constructors and Methods 365 ArrayList’s Pitfalls 367 Lab: Creating an Index for a Document 370 Case Study and Lab: GridWorld Critters 374 Summary 377 Exercises 378 Prologue Copyright © 2011 by Skylight Publishing 361 .2 13.util.3 13.6 13.ArrayList 13.capacity size Chapter13 13 java.5 13.

i++) temp[i] = arr[i]. The capacity is the length of the currently allocated array that holds the list values.util. you have to create a new array of a larger size. If an array is full and you want to add an element. copy all the values from the old array into the new array.. // double the size for (int i = 0. the ArrayList automatically increases its capacity by executing code similar to the fragment shown above. Copyright © 2011 by Skylight Publishing 13. an ArrayList allows you to keep a list of values in an array. then reassign the old name to the new array.362 CHAPTER 13 ~ java. The size is the number of elements currently stored in the list. arr = temp. . For example: Object[] arr = new Object[someSize]..length. If you know in advance the maximum number of values that will be stored in an array.1 Prologue Java arrays are convenient and safe. . The ArrayList keeps track of its capacity and size (Figure 13-1). The library class ArrayList from the java. i < arr.util package provides that functionality.2 ArrayList’s Structure As the name implies. its size cannot change. When the size reaches ArrayList’s capacity and you need to add an element. However. you can declare an array of that size from the start. Object[] temp = new Object[2 * arr.ArrayList 13. The old array is eventually recycled by the Java garbage collector. they have one limitation: once an array is created.length]. But then you have to keep track of the actual number of values stored in the array and make sure you do not refer to an element that is beyond the last value currently stored in the array.

import java. The capacity and size of an ArrayList The ArrayList class provides the get and set methods.util.util.ArrayList.List java. an ArrayList has convenient methods to add and remove an element.LinkedList. These methods check that 0 ≤ i < size. add import java.LinkedList LinkedList has the same methods as ArrayList (and a few additional methods).util. This is explained in more detail in Section 20.util.List: class. Copyright © 2011 by Skylight Publishing at the top of your source file. which access and set the i-th element.ArrayList. The ArrayList class is part of the Java collections framework and implements the java.util.List interface. In addition. respectively.util. also implements «interface» java.2 ~ ArrayList’S STRUCTURE 363 capacity size "Apple" "Orange" "Peach" Figure 13-1.3 (Chapter 20).util.util. From a more abstract point of view.13. an ArrayList represents a “list” of objects. . A “list” holds several values arranged in a sequence and numbered.util. java.List and java. library Another java. but it uses a different data structure to store the list elements.List.ArrayList java. If your class uses java.util.

Starting with Java 5. and return values. etc. Syntactically. method parameters.0. For it to work.add(word). For example: private ArrayList<String> names. which is read “an ArrayList of sometypes. for (String word : words) if (word.). The type is placed in angle brackets after ArrayList. If you try to add a value of a primitive data type to a list.” You need to use the whole thing whenever you use the ArrayList type: in declaring variables. return words5. that wrapper type must match the declared type of the list elements. For example: // Returns an ArrayList with the elements from words // that have 5 or more letters public ArrayList<String> fiveOrLonger(ArrayList<String> words) { ArrayList<String> words5 = new ArrayList<String>().length() >= 5) words5. you should specify the type of its elements. the whole combination ArrayList<sometype> acts as one long class name. can only hold objects. . the compiler will convert that value into an object of a corresponding wrapper class (Integer.364 CHAPTER 13 ~ java. and when you create an ArrayList. or private ArrayList<Actor> actors. when you declare an ArrayList.ArrayList An ArrayList holds objects of a specified type. An ArrayList.util. like other kinds of Java collections. } Copyright © 2011 by Skylight Publishing Note that a “for each” loop works for ArrayLists and is a convenient way to traverse an ArrayList. Double.

add(5).0)). .size() .1. But samples.13. elmt) methods. otherwise these methods throw an IndexOutOfBoundsException. (We’ll examine add and other ArrayList methods in the next section. // can't add an int to an ArrayList<Double> won’t work. If you know in advance the maximum number of values that will be stored in your list. The ArrayList class implements over two dozen methods (specified in the List interface).3 ArrayList’s Constructors and Methods Copyright © 2011 by Skylight Publishing ArrayList’s no-args constructor creates an empty list (size() == 0) of the default capacity (ten). but we will discuss only a subset of more commonly used methods. In the get(i) and set(i. and we do the same. ArrayList(int capacity).0). Another constructor. it is better to create an ArrayList of that capacity from the outset to avoid later reallocation and copying of the list.add(5. ArrayList<Double> samples = new ArrayList<Double>(). (Java API docs use the letter E to refer to the type of ArrayList elements. This is called autoboxing. the parameter i must be in the range from 0 to list. the elements in an ArrayList are numbered by their indices from 0 to list. null). An ArrayList can also hold nulls after calls to add(null) or add(i. works and is the same as ArrayList<Double> samples = new ArrayList<Double>().) As we’ve noted.3 ~ ArrayList’S CONSTRUCTORS AND METHODS 365 For example.1. Some of the ArrayList’s methods are shown in Figure 13-2.add(new Double(5. creates an empty list with a given initial capacity. samples.) 13. samples. For example: ArrayList<String> names = new ArrayList<String>(10000).size() .

elmt2. shifts the element currently at that position and the subsequent elements to the right (increments their indices by one) Returns the value of the i-th element Replaces the i-th element with elmt. E elmt) works the same as add(E elmt). This method checks that 0 ≤ i ≤ list. .. returns the old value Removes the i-th element from the list and returns its value. It also increments the size of the list by one.ArrayList int size() boolean isEmpty() boolean add(E elmt) void add(int i. E elmt) E remove(int i) boolean contains(Object obj) int indexOf(Object obj) Copyright © 2011 by Skylight Publishing String toString() // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Returns the number of elements currently stored in the list Returns true if the list is empty. so that elmt becomes the i-th element. E elmt) E get(int i) E set(int i.size(). This method shifts the old i-th element and all the subsequent elements to the right and increments their indices by one. E elmt). add(int i. The add method is overloaded: the version with two parameters.util.. returns true Inserts elmt into the i-th position. Commonly used ArrayList<E> methods The add(E elmt) method appends elmt at the end of the list and increments the size of the list by one.size() and throws IndexOutOfBoundsException if it isn’t.. If called with i = list. . shifts the subsequent elements (if any) to the left (decrements their indices by 1) Returns true if this list contains an element equal to obj (the equals method is used for comparison) Returns the index of the first occurrence of obj in this list. otherwise returns false Appends elmt at the end of the list. inserts elmt into the list.366 CHAPTER 13 ~ java. or -1 if obj is not found (the equals method is used for comparison) Returns a string representation of this list as [elmt1. then add(int i. elmtN] Figure 13-2.

equals(obj)) .. and decrements their indices. which gives direct access to the element with a given index. because the elements are stored in an array. Inserting or removing an element at the beginning or somewhere in the middle of an ArrayList is less efficient. They need some way to compare obj to the elements of the list. Copyright © 2011 by Skylight Publishing Therefore. This is accomplished by calling obj’s equals method.4 ~ ArrayList’S PITFALLS 367 The remove(i) method removes the i-th element from the list. Double. The convenient toString method allows you to get a string representation of a list and to print the whole list in one statement. shifts all the subsequent elements (if any) to the left by one.println(list). ArrayList implements the get and set methods very efficiently.out. We will explain how to define equals for your own classes in Chapter 14. For example: System. of course. The indexOf(Object obj) and contains(Object obj) methods are interesting. for Integer.get(i).13. Appropriate equals methods are defined. intends to remove all occurrences of the word "like" from an ArrayList<String>: . something like this: if (list.. String. Adding an element may occasionally require reallocation and copying of the array. remove returns the value of the removed element. 13. It also decrements the size of the list by one. which may be time-consuming for a long list. you should make sure a reasonable equals method is defined for your objects if you plan to place them into an ArrayList. because it requires shifting the subsequent elements. for example. The list will be displayed within square brackets with consecutive elements separated by a comma and a space.4 ArrayList’s Pitfalls You have to be careful with the add and remove methods: keep in mind that they change the size of the list and the indices of the subsequent elements and The following innocent-looking code.

equals(obj2)). obj1 == obj2). i++) { if ("like".get(i))) words. The correct code should increment i only if the word is not removed.remove(i). i < n. i < words... obj1. for (int i = 0. It can hold duplicate values — not only equal objects (that is. while (i < words.equals(words.get(i))) words. after the first "like" is found and removed. And that is not all. the program will be aborted with an IndexOutOfBoundsException. } An ArrayList holds references to objects.util. but also several references to the same object (that is. for (int i = 0.size()) { if ("like".equals(words.size().ArrayList ArrayList<String> words = new ArrayList<String>(). .368 CHAPTER 13 ~ java. Even if we fix this bug by getting rid of n — ArrayList<String> words = new ArrayList<String>(). . else i++. the second one will not be removed. Then i is incremented in the for loop. the next word is skipped. } Copyright © 2011 by Skylight Publishing — another bug still remains. Once i goes past the new list size. int n = words. .size().equals(words. i++) { if ("like".. As a result. } However. For example: int i = 0.remove(i). When an occurrence of "like" is removed.get(i))) words.remove(i). the subsequent words are shifted to the left. the size of the list words is decremented and becomes smaller than n.. If "like" occurs twice in a row.

Claire] as expected (Figure 13-3-a).length. are executed. which sets the person’s name. i < names. } return list. for example. "Claire"}. } Copyright © 2011 by Skylight Publishing After the statements String[] names = {"Alice".add(new Person(names[i])).println(guests).13.out. list. Version 1: public ArrayList<Person> makeGuestList(String[] names) { ArrayList<Person> list = new ArrayList<Person>(). the following two versions of the method makeGuestList that builds a list of people (objects of the class Person) from a given array of names. List<Person> guests = makeGuestList(names). "Bob". Let’s assume that the class Person has the constructors used in the code and a setName method. } Version 2: public ArrayList<Person> makeGuestList(String[] names) { ArrayList<Person> list = new ArrayList<Person>().length. System. Version 1 displays [Alice. Bob.add(p). return list.setName(names[i]).4 ~ ArrayList’S PITFALLS 369 It is important to understand that an object can change after it has been added to a list (unless that object is immutable) and that the same object can belong to several ArrayLists. i++) { p. for (int i = 0. Person p = new Person(). Consider. for (int i = 0. i < names. i++) list. .

displays [Claire.5 Lab: Creating an Index for a Document In this lab you will write a program that reads a text file and generates an index for it.ArrayList Version 2. (b) A list with references to the same object Copyright © 2011 by Skylight Publishing 13. (a) Alice Bob Claire (b) Alice Bob Claire Figure 13-3. All the words that occur in the text should be listed in the index in upper case in alphabetical order. however. Claire] because the list contains three references to the same object (Figure 13-3-b). (a) A list with references to different objects.370 CHAPTER 13 ~ java. Figure 13-4 shows an example. . Claire. Adding this object to the list does not shield it from being modified by the subsequent setName calls.util. Each word should be followed by a list of all the line numbers for lines that contain that word.

14 LOT 15 NEW 9 OF 16 OLD 8 ONE 1. fishIndex. This one has a little star. IndexMaker classes . and DocumentIndex extends ArrayList<IndexEntry>. 7 CAR 14 FISH 1. It also uses ArrayList in two ways: IndexEntry has an ArrayList<Integer> field that holds the line numbers. 16 HAS 11.5 ~ LAB: CREATING AN INDEX FOR A DOCUMENT 371 fish.13. 3.util ArrayList IndexMaker DocumentIndex IndexEntry Figure 13-5. 6.txt A 12. 14 TWO 2 WHAT 15 Figure 13-4.txt One fish two fish red fish blue fish. 14 RED 3 SAY 15 STAR 12 THERE 16 THIS 11. 15 ARE 16 BLACK 6 BLUE 4. 14. 4. 8. 14 LITTLE 12. Say! What a lot of fish there are. A sample text file and its index Copyright © 2011 by Skylight Publishing The Index Maker program consists of three classes (Figure 13-5). Black fish blue fish old fish new fish. This one has a little car. 2. java. 11. 9. 7.

opens the input file. (Note that the IndexEntry class is quite general and reusable: the numbers can represent line numbers.util. You will need to convert num into an Integer to call numsList’s contains method. reads and processes all the lines from the input file. but only if it is not already in that list.372 CHAPTER 13 ~ java. Copyright © 2011 by Skylight Publishing The numbers in numsList represent the line numbers where word occurs in the input file. 3. then saves the resulting document index in the output file. The constructor should also initialize numsList to an empty ArrayList<Integer>. You don’t have to deal with reading or writing files in this lab. converts it into the upper case (by calling toUpperCase). The IndexEntry class An IndexEntry object represents one index entry. . String getWord() — this is an accessor method. and saves it in word.. private ArrayList<Integer> numsList. It has two fields: private String word.ArrayList The IndexMaker class is the main class. This class should have the following three methods: 1. Writing the DocumentIndex and IndexEntry classes is left to you (possibly in a team with another programmer). String toString() — returns a string representation of this IndexEntry in the format used in each line of the output file (Figure 13-4). creates an output file. depending on the application.) Provide a constructor for this class that takes a given word (a String). 2. void add(int num) — appends num to numsList. etc. We have provided this class for you in JM\Ch13\IndexMaker. Its main method prompts the user for the names of the input and output files (or obtains them from command-line arguments. it returns word. if supplied). page numbers.

\W (with an uppercase ‘W’) stands for any “non-word” character. regex. + means “occurs at least once. regex describes the match pattern for all possible word separators. Use a “for each” loop to call addWord for each word in that array. as shown in Figure 13-4. . Note. hence the double backslash in the literal string. of course. the other that creates a list with a given capacity. We recommend that you also define a private helper method private int foundOrInserted(String word) and call it from addWord. void addAllWords(String str. (These constructors simply call the respective constructors of the superclass. int num) — adds num to the IndexEntry for word by calling that IndexEntry’s add(num) method. ArrayList. void addWord(String word. that split may put an empty string into the resulting array — when str starts with a separator or when str is empty. however. a regular expression regex. Copyright © 2011 by Skylight Publishing You could code the word extractor yourself. Provide two constructors: one that creates a list with the default capacity. Use the one that takes one parameter. int num) — extracts all the words from str (skipping punctuation and whitespace) and for each word calls addWord(word. Regular expressions are not specific to Java: they are used in many languages and text parsers.5 ~ LAB: CREATING AN INDEX FOR A DOCUMENT 373 The DocumentIndex class A DocumentIndex object represents the entire index for a document: the list of all its index entries.) DocumentIndex should have the following two public methods: 1. Make sure you skip empty strings and do not call addWord for them. any character that is not a digit or a letter. Make the DocumentIndex class extend ArrayList<IndexEntry>. This method should traverse this DocumentIndex and compare word (case-blind) to the words in the IndexEntry objects in this list.13. Look it up in the Java API. 2. num). The index entries should always be arranged in alphabetical order.” (Regular expressions use backslash as the escape character. but it is much better to use the String class’s split method. that is. This is an unfortunate decision (or a bug).) split returns an array of Strings. the method first creates a new IndexEntry for word and inserts it into this list in alphabetical order (ignoring the upper and lower case). that is. If word is not yet in this DocumentIndex. Use "\\W+" here.

13.374 CHAPTER 13 ~ java. which limit the things you are allowed to do.ArrayList looking for the position where word fits in alphabetically. and it overrides Actor’s act method: public void act() { if (getGrid() == null) return.6 Case Study and Lab: GridWorld Critters Part 4 of the GridWorld Student Manual introduces the class Critter and gives examples of two of its subclasses: ChameleonCritter and CrabCritter. selectMoveLocaton. Location loc = selectMoveLocation(moveLocs). a file with blank lines. but you have to pay attention to their specifications and strict postconditions. you are supposed to leave its act method alone and work with the five act calls: getActors. } Copyright © 2011 by Skylight Publishing You can. the method creates and inserts a new IndexEntry for word at that position. makeMove(loc). processActors(actors). ArrayList<Location> moveLocs = getMoveLocations(). including an empty file. override the act method in Critter’s subclasses. helper methods that getMoveLocations. processActors. . You can redefine any of these five methods in your subclass of Critter. What are these rules? When you create a subclass of Critter.util. If an IndexEntry with word is not already in that position. Critter is a subclass of Actor. and makeMove. a file with multiple occurrences of a word on the same line. Critter’s methods make extensive use of the ArrayList class. and a file with the same word on different lines.” These rules were defined to help focus your attention on how best to design subclasses and how to follow specifications and satisfy postconditions in methods. Test your program thoroughly on different text data files. of course. but that would violate the “rules of the game. which gives us an opportunity to practice using it. The method returns the position (we’d like to say “the index” but we have too many indices going already!) of the either found or inserted IndexEntry. ArrayList<Actor> actors = getActors(). a file with lines that have leading spaces or punctuation.

In Critter this method returns the list of empty adjacent locations. Again. Suppose. such as location. the makeMove method moves this critter from its current location to Location loc passed to makeMove. Then you are allowed to increment the age field only in processActors or makeMove. and the attributes that you might introduce yourself. this method cannot change the state of any actor. All the attributes of each actor. such as age or steps. this critter is removed from the grid. The getMoveLocations method returns a list of locations to which this critter can potentially move. you want to keep track of the “age” of your critter (the number of calls to its act method since the critter was created). getActors returns the list of all actors in locations adjacent to this critter. Copyright © 2011 by Skylight Publishing . In Critter itself. direction. only processActors and makeMove can change the state of an actor in the grid. replacing its current occupant. makeMove can only change the state of this critter. and place a new actor in its old location. makeMove’s postcondition allows you to change this critter’s state but not the state of any other actor. must remain unchanged. getActors’s postcondition stipulates that “the state of all actors is unchanged.13.” Therefore. You can also remove any of the actors in actors from the grid and place new actors in empty grid locations. In makeMove you can add a new actor in this critter’s old location. To summarize. this method’s postcondition stipulates that it doesn’t change the state of any actor. if the list is empty. Like getActors. makeMove can move this critter to a new location. Finally. processActors can remove actors from a given list and place new actors in empty locations. If loc is null. In Critter this method chooses a location from the list randomly or. processActors can change the state of this critter (except its location) and the state of any actor from a list passed to it. The postcondition of the processActors method is more liberal: it allows you to change the state of this critter (except its location) and the states of any of the actors in the actors list passed to processActors.6 ~ CASE STUDY AND LAB: GRIDWORLD CRITTERS 375 The getActors method returns a list of actors for “processing. this method cannot change the values of any fields in any of the actors in the grid. color. returns this critter’s current location.” In Critter itself. The selectMoveLocaton method selects one of the locations from the list of locations passed to it. this method “eats” (removes from the grid) all actors in actors except rocks and other critters. for example. if any.

1.” You can do it individually or in a group with other developers. between loc1 and loc2 is defined as the largest of the absolute values of loc1. a Mosquito. artists. Study Critter’s source code and do some of the exercises on pages 35-36. Do not define an act method. Read Part 4 of the GridWorld Student Manual. Set Cow’s color in its constructor. and so on. then dies. it first lays eggs in all empty locations adjacent to its location. You will need to override Critter’s processActors and selectMoveLocation methods. override Critter’s selectMoveLocation method. and quality assurance specialists. Define a class Cow as a subclass of Critter. processActors cannot move this critter.util. A cow moves slowly. Define another critter. making a move on every third step (every third call to its act method). but it eats only Flowers and destroys MosquitoEggs in all adjacent locations. First create a list bestLocs of all the locations from locs that are at the same minimal distance to a cow. Copyright © 2011 by Skylight Publishing . Then randomly choose and return one of them.getRow()-loc2.getRow() and loc1.376 CHAPTER 13 ~ java. If it cannot bite a cow (get into a location adjacent to a cow) in that time. A Cow acts like a regular critter. If it does bite a cow. A Mosquito aims to bite a cow and lay eggs.getCol()-loc2.getCol().java for an example).ArrayList These rules force you to do things where they belong. it dies. Location loc2). Mosquito’s life span is only 6 steps. Write a helper class DistanceBetweenLocations with only one static The distance method. 2. A Mosquito moves to one of the adjacent locations closest to the nearest cow. Set Mosquito’s color in the constructor. In this lab you will create two subclasses of Critter and one subclass of Actor to create a simple GridWorld “ecosystem. Make the mosquito turn toward the new location as it moves (see ChameleonCritter. distance(Location loc1. Override Critter’s processActors method to achieve this functionality. No need to duplicate code from Critter’s selectMoveLocation: just call super. selectMoveLocation cannot remove any actors from the grid. In your Mosquito class.selectMoveLocation(bestLocs).

. The get(i).. 4. ArrayList holds elements of a specified type. and the indexOf method returns the index of a given value (or -1 if not found). The add methods need to allocate more memory and copy the whole list when the list’s capacity is exceeded. (We have decided to skip the larva and pupa stages in the mosquito life cycle to keep things simple.) Write a PastureRunner class. Create or find on the Internet images of a cow. The most commonly used ArrayList methods are shown in Figure 13-2.13. three Cows and several MosquitoEggs into the grid. another constructor creates an empty list of a specified capacity. Redefine Actor’s act method to achieve this. The add(i. set(i. because they require shifting of the elements that follow the i-th element. An ArrayList keeps track of the list’s capacity (the length of the allocated array) and its size (the number of elements currently in the list). Starting with Java 5. Place a couple of Rocks. and remove(i) methods check that i is from 0 to size() . . On the sixth step it turns into a Mosquito. Test your program thoroughly.1 (from 0 to size() in case of add) and throw an IndexOutOfBoundsException if an index is out of the valid range. The contains method checks whether a given value is in the list. obj). obj) methods are efficient because an array provides random access to its elements. add(i. ArrayList’s get(i) and set(i. 6. The no-args constructor creates an empty list of some small default capacity. a mosquito. When an ArrayList is full and we add a value. 5. The add(obj) method appends an element at the end of the list. the ArrayList increases its capacity automatically by allocating a larger array and copying all the elements into it. similar to CritterRunner. obj) and remove(i) Copyright © 2011 by Skylight Publishing methods are on average less efficient.7 Summary The java.ArrayList class helps implement “dynamic arrays” — arrays that can grow as needed. Define a class MosquitoEgg as a subclass of Actor.0. obj).util. and a mosquito egg and save them in 48-by-48-pixel gif files. two or three Bugs. 13. ArrayList doesn’t work with values of a primitive data types — they are converted to objects of the corresponding wrapper class. The add and remove methods adjust the indices of the subsequent elements and the size of the list.7 ~ SUMMARY 377 3. A MosquitoEgg just sits there doing nothing for five steps.

. List<String> words = new ArrayList<String>().. _____ Two variables can refer to the same ArrayList. x) calls more efficient 3. ArrayList<String> words = new List<String>(). // process elmt } — works for an ArrayList as well as for a one-dimensional array. Exercises Sections 13.util. _____ ArrayList’s remove method destroys the object after it has been removed from the list.1-13. _____ Copyright © 2011 by Skylight Publishing 2. x) calls more efficient will make get(i) and set(i. Which of the following declarations will compile with no errors? (a) (b) (c) (d) ArrayList<String> words = new ArrayList<String>().5 1. _____ ArrayList’s add method makes a copy of the object and adds it to the list. A list is allowed to hold null references and multiple references to the same object..ArrayList An ArrayList holds references to objects.378 CHAPTER 13 ~ java. ArrayList<String> words = new ArrayList<String>(50). The “for each” loop — for (E elmt : list) { . which trims the capacity of the list to its current size. _____ The same object may belong to two different ArrayLists. The ArrayList class has a method trimToSize(). An object can be changed after it is added to the list (unless the object is immutable). True or false? Calling this method (a) (b) (c) (d) will save space in the program. Mark true or false and explain: (a) (b) (c) (d) (e) An ArrayList can contain multiple references to the same object. will make add(x) calls more efficient will make add(0.

. The original list should remain unchanged. "A". "A"]. ArrayList<Object> list2) 6. "C".add(1). lst. "B". a negative integer if this is less than other. 2). What is the output from the following code? ArrayList<Integer> lst = new ArrayList<Integer>(). 8. lst.CHAPTER 13 ~ EXERCISES 379 4. } Hint: traverse backwards. 7. "A"]. lst.remove(_______________). Copyright © 2011 by Skylight Publishing that removes from list1 all objects that are also in list2. 0). public void removeConsecutiveDuplicates(ArrayList<String> lst) { for (________________________________________________) if (_________________________________________________) lst.add(2). lst.add(0). lst. For example.out. "C".add(0. Write and test a method public void filter(ArrayList<Object> list1. "A".println(lst). and 0 if this is equal to other. "C". Write a method that removes the smallest value from an ArrayList<Integer>. "B". which removes consecutive duplicate values from an ArrayList of strings. Hint: the contains and indexOf methods cannot be used. Hint: Integer has a method compareTo(Integer other) that returns a positive integer if this is greater than other. if letters contains ["A". 5. not equals. Write a method that takes an ArrayList<String> and returns a new ArrayList<String> in which the elements are stored in reverse order.add(1. 1). System. after a call to removeConsecutiveDuplicates(letters) letters should contain ["A". Fill in the blanks in the method removeConsecutiveDuplicates. "A".add(2. lst. Your method should compare the objects using the == operator.

14... in the same order as they appear in words. A Painter acts like a Critter. Your method should traverse the list words only once and leave it unchanged. throws them into 26 “buckets. If the sum is less than n.” according to the first letter. Don’t forget to remove the last added value before trying the next one. CHAPTER 13 ~ java. list) again. The first bucket should contain all the strings from words that start with an ‘a’. 10. Write a method that implements Grid’s getValidAdjacentLocations method.. Is it possible to do this in such a way that new bugs will act exactly the same way as old bugs in any GridWorld program? 13.. white. only instead of “eating” neighbors it paints them randomly into red. (b) . using Location’s getAdjacentLocation method and Grid’s isValid method. If the sum of the values in list is n. ArrayList<Integer> list). write a recursive helper method displayPartitions(int n. and so on. A partition of a positive integer n is its representation as a sum of positive integers: n = p1 + p2 + . just print these values.util. Consider only partitions where p1 ≤ p2 ≤ . which contains strings of alphabetic characters. Review GridWorld’s Location class and Grid interface. try appending to the list another integer. Each bucket should be represented by an ArrayList<String>.ArrayList Can an ArrayList<Object> be its own element? Test this hypothesis.6-13. ≤ pk . Write and test a method that takes a List<String> words. or blue color. (a) Rewrite GridWorld’s Bug class as a subclass of Critter. 11. + pk . and returns the ArrayList of buckets. Write a method that prints out all possible partitions of a given positive integer n. Copyright © 2011 by Skylight Publishing Hint: use an ArrayList<Integer> of capacity n to hold a partition.380 9. and call displayPartitions(n. the second bucket should contain all the strings that start with a ‘b’. Write and test a GridWorld’s Painter class. in the range from the last value in the list (or 1. Sections 13.7 12. if the list was empty) to n .sum. Do not override Critter’s act method and make sure all the postconditions in Critter’s methods are satisfied.

Sign up to vote on this title
UsefulNot useful