CS211 Chapter10
What is an ArrayList? In what cases should you use an ArrayList rather than an array?
An ArrayList is a structure that stores a collection of objects inside itself as elements. Each element is associated with an integer index starting from 0. You should use an ArrayList instead of an array if you don't know how many elements you'll need in advance, or if you plan to add items to or remove items from the middle of your dataset.
Which of the following is the correct syntax to construct an ArrayList to store integers?
ArrayList<Integer> list = new ArrayList<Integer>();
Write code to declare an ArrayList holding the first 10 multiples of 2: 0, 2, 4,..., 18. Use a loop to fill the list with the proper elements.
ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { numbers.add(2 * i); }
Write the code to declare an ArrayList containing these elements. What is the size of the list? What is its type? ["It", "was", "a", "stormy", "night"]
ArrayList<String> list = new ArrayList<String>(); list.add("It"); list.add("was"); list.add("a"); list.add("stormy"); list.add("night"); The list's type is ArrayList<String> and its size is 5.
Write code to change the second element's value to "IS", producing the following ArrayList as the result: ["It", "IS", "a", "dark", "and", "stormy", "night"]
Code to change the second element's value to "IS": list.set(1, "IS");
When the code that follows runs on an ArrayList of Strings, it throws an exception. Why? for (String s: words) { System.out.println(s); if (s.equals("hello")) { words.add("goodbye"); } }
The code throws a ConcurrentModificationException because it is illegal to modify the elements of an ArrayList while for-each looping over it.
Describe how to arrange an ArrayList into sorted order. What must be true about the type of elements in the list in order to sort it?
To arrange an ArrayList into sorted order, call the Collections.sort method on it. For example, if your ArrayList is stored in a variable named list, you would call: Collections.sort(list); For this to work, the type of the objects stored in the list must be Comparable.
Write the output produced when the following method is passed each of the following lists: public static void mystery1(ArrayList<Integer> list) { for (int i = list.size() - 1; i > 0; i--) { if (list.get(i) < list.get(i - 1)) { int element = list.get(i); list.remove(i); list.add(0, element); } } System.out.println(list); } [2, 6, 1, 8] [30, 20, 10, 60, 50, 40] [-4, 16, 9, 1, 64, 25, 36, 4, 49]
[1, 2, 6, 8] [10, 30, 40, 20, 60, 50] [-4, 1, 25, 4, 16, 9, 64, 36, 49]
Write the output produced when the following method is passed each of the following lists: public static void mystery2(ArrayList<Integer> list) { for (int i = list.size() - 1; i >= 0; i--) { if (i % 2 == 0) { list.add(list.get(i)); } else { list.add(0, list.get(i)); } } System.out.println(list); } [10, 20, 30] [8, 2, 9, 7, 4] [-1, 3, 28, 17, 9, 33]
[20, 10, 20, 30, 30, 20] [8, 7, 8, 2, 9, 7, 4, 4, 2, 8] [33, 28, 33, -1, 3, 28, 17, 9, 33, 17, -1, 33]
Write the output produced when the following method is passed each of the following lists: public static void mystery4(ArrayList<Integer> list) { for (int i = 0; i < list.size(); i++) { int element = list.get(i); list.remove(i); list.add(0, element + 1); } System.out.println(list); } [10, 20, 30] [8, 2, 9, 7, 4] [-1, 3, 28, 17, 9, 33]
[31, 21, 11] [5, 8, 10, 3, 9] [34, 10, 18, 29, 4, 0]
public static void mystery3(ArrayList<Integer> list) { for (int i = list.size() - 2; i > 0; i--) { int a = list.get(i); int b = list.get(i + 1); list.set(i, a + b); } System.out.println(list); } [72, 20] [1, 2, 3, 4, 5, 6] [10, 20, 30, 40]
[72, 20] [1, 20, 18, 15, 11, 6] [10, 90, 70, 40]
["It", "IS", "a", "dark", "and", "stormy", "night"] write a for-each loop that prints the uppercase version of each String in the list on its own line.
for (String s : list) { System.out.println(s.toUpperCase()); }
Write code to remove from the list any Strings that contain the letter "a". The following should be the list's contents after your code has executed: ["It", "IS", "stormy", "night"]
for (int i = 0; i < list.size(); i++) { if (list.get(i).indexOf("a") >= 0) { list.remove(i); i--; // so the new element i will be checked } }
Write code to insert two additional elements, "dark" and "and", at the proper places in the list to produce the following ArrayList as the result: ["It", "was", "a", "dark", "and", "stormy", "night"]
list.add(3, "dark"); list.add(4, "and");
Consider the following variable declarations: Integer n1 = 15; Integer n2 = 7; Integer n3 = 15; String s1 = "computer"; String s2 = "soda"; String s3 = "pencil"; Indicate whether the result of each of the following comparisons is positive, negative, or 0: n1.compareTo(n2) n3.compareTo(n1) n2.compareTo(n1) s1.compareTo(s2) s3.compareTo(s1) s2.compareTo(s2)
n1.compareTo(n2) > 0 n3.compareTo(n1) == 0 n2.compareTo(n1) < 0 s1.compareTo(s2) < 0 s3.compareTo(s1) > 0 s2.compareTo(s2) == 0
Write a method called maxLength that takes an ArrayList of Strings as a parameter and that returns the length of the longest String in the list. If your method is passed an empty ArrayList, it should return 0.
public static int maxLength(ArrayList<String> list) { int max = 0; for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.length() > max) { max = s.length(); } } return max; }
What is a natural ordering? How do you define a natural ordering for a class you've written?
A natural ordering is an order for objects of a class where "lesser" objects come before "greater" ones, as determined by a procedure called the class's comparison function. To give your own class a natural ordering, declare it to implement the Comparable interface and define a comparison function for it by writing an appropriate compareTo method.
What is a wrapper class? Describe the difference between an int and an Integer.
A wrapper class is one whose main purpose is to act as a bridge between primitive values and objects. An Integer is an object that holds an int value. Wrappers are useful in that they allow primitive values to be stored into collections.
Write code to read a line of input from the user and print the words of that line in sorted order, without removing duplicates. For example, the program output might look like the following: Type a message to sort: to be or not to be that is the question Your message sorted: be be is not or question that the to to
Scanner console = new Scanner(System.in); System.out.print("Type a message to sort: "); String message = console.nextLine(); ArrayList<String> words = new ArrayList<String>(); Scanner lineScan = new Scanner(message); while (lineScan.hasNext()) { words.add(lineScan.next()); } System.out.print("Your message sorted: "); Collections.sort(words); for (String word : words) { System.out.print(word + " "); } System.out.println(); // to end the line of output
Use the compareTo method to write code that reads two names from the console and prints the one that comes first in alphabetical order. For example, the program's output might look like the following: Type a name: Tyler Durden Type a name: Marla Singer Marla Singer goes before Tyler Durden
Scanner console = new Scanner(System.in); System.out.print("Type a name: "); String name1 = console.nextLine(); System.out.print("Type a name: "); String name2 = console.nextLine(); if (name1.compareTo(name2) < 0) { System.out.println(name1 + " goes before " + name2); } else if (name1.compareTo(name2) > 0) { System.out.println(name1 + " goes after " + name2); } else { // equal System.out.println(name1 + " is the same as " + name2); }
Write code to print out whether or not a list of Strings contains the value "IS". Do not use a loop.
System.out.println(list.contains("IS"));
["It", "IS", "a", "dark", "and", "stormy", "night"] write code to print out the index at which your list contains the value "stormy" and the index at which it contains "dark". Do not use a loop.
System.out.println(list.indexOf("stormy")); System.out.println(list.indexOf("dark"));
The code that follows does not compile. Why not? Explain how to fix it. ArrayList<int> numbers = new ArrayList<>(); numbers.add(7); numbers.add(19); System.out.println(numbers);
The code doesn't compile because primitives cannot be specified as type parameters for generic types. The solution is to use the "wrapper" type Integer instead of int. Change the line declaring the ArrayList to the following: ArrayList<Integer> numbers = new ArrayList<Integer>();
