Reading data
Since an ArrayList will expand as needed when we add elements, it is ideal for reading data from an input stream. To read data into an array, we would have to know in advance how many items there will be, which normally requires reading the data twice - once to count the items, and a second time to fill the array.With an ArrayList, we can just add elements as they are read. Here is an example that parses a string and puts the values into an ArrayList:
public static ArrayList<Integer> readNumbers(String text) { Scanner scanner = new Scanner(text); ArrayList<Integer> nums = new ArrayList<Integer>(); scanner = new Scanner(text); while (scanner.hasNextInt()) { nums.add(scanner.nextInt()); } return nums; }To try out this code see the complete example ArrayListExample1.java
Note that if what we really want is an int array of the correct size, we can create it after reading the data and copy everything over.
public static int[] readNumbers(String text) { Scanner scanner = new Scanner(text); ArrayList<Integer> nums = new ArrayList<Integer>(); scanner = new Scanner(text); while (scanner.hasNextInt()) { nums.add(scanner.nextInt()); } int[] ret = new int[nums.size()]; for (int i = 0; i < nums.size(); i += 1) { ret[i] = nums.get(i); } return ret; }See ArrayListExample2.java
Note that there is a method toArray
in the ArrayList class that converts an ArrayList to an array, but we can't use it here: we specifically need to return an array of int, and the toArray
method would return an array of the wrapper type Integer
.
Checkpoint 2
Write a methodpublic static String[] removeDuplicates(String[] words)that removes duplicates from an array of strings. More precisely, the method returns a new array containing the strings in
words
, without any duplicates. The given array words
is not modified.
The simplest approach is to create an ArrayList without the duplicates, and then create the new array and copy items over. Note that ArrayList has a method contains
that tells you whether a given object is in the list. Here, it is possible to use the method toArray
to create the array, but the usage is a bit odd. If myList
is an ArrayList of Strings and you want to convert it to an array of Strings, it looks like
String[] theArray = myList.toArray(new String[]{});
(For reasons that are way too esoteric to get into here, it turns out that, at runtime, the ArrayList does not actually know the type of the elements that it contains, so the argument to the method is an empty array of String whose purpose is to enable toArray
to create an array of correct type to return.)