Page 465 - Introduction to Programming with Java: A Problem Solving Approach
P. 465
Review Question Solutions 431 in the first evenNumbers element, put 2 in the second evenNumbers element, . . . , put 18 in the tenth
evenNumbers element. You must use a standard for loop for your code fragment.
20. [after §10.13] Provide a more elegant (but functionally equivalent) version of this code fragment:
ArrayList<Car> cars = new ArrayList<Car>();
Car car1 = new Car("Mustang", 2006, "tiger-striped");
cars.add(car1);
Car car2 = new Car("MiniCooper", 2006, "lime green");
cars.add(car2);
21. [after §10.13] Suppose you have an ArrayList of street addresses that’s been initialized and filled as follows:
ArrayList<String> addressList = new ArrayList<String>();
addressList.add("1600 Pennsylvania Avenue");
addressList.add("221B Baker Street");
...
addressList.add("8700 N.W. River Park Drive");
Provide a for-each loop (not a standard for loop) that prints the addressList’s addresses, one address per line.
22. [after §10.14] Suppose you wanted to maintain a list of cities described by the City class defined in Exercise 16. And suppose you wanted to be able to insert or remove cities at any place in the list to
maintain a certain ordering as you added or removed elements. Should you use an array or an ArrayList, and why?
Apago PDF Enhancer
Review Question Solutions
1. False. The types of the data elements in a particular array must be the same.
2. True.
3. Declaration for an array of strings called names:
String[] names;
4. The args parameter in main is an array of strings.
5. The elements of an array are like the instance variables in an object. Array-element default values are not
garbage. The default value of a char[] element is a special character whose underlying numeric value is 0.
6. False. The largest acceptable index value is one less than the array’s length.
7. This code fragment initializes the character array, alphabet:
for (int i=0; i<26; i++)
{
}
alphabet[i] = letters.charAt(i);
8. You can copy:
arr1[] = {'x', 'y', 'z'}
to the end of:
arr2[] = new char[26]