Java Reference
In-Depth Information
Table 10.1
Basic ArrayList Methods
Method
Description
ArrayList<String> example
add(value )
adds the given value at the end of
list.add("end");
the list
adds the given value at the given index,
add(index, value)
list.add(1, "middle");
shifting subsequent values right
removes all elements from the list
clear()
list.clear();
gets the value at the given index
get(index)
list.get(1)
removes the value at the given
remove(index)
list.remove(1);
index, shifting subsequent values left
replaces the value at the given
set(index, value)
list.set(2, "hello");
index with the given value
returns the current number of elements
size()
list.size()
in the list
You can construct an ArrayList<String> to hold these names and use the
contains method to ensure that there are no duplicates:
// removes duplicates from a list
Scanner input = new Scanner(new File("names.txt"));
ArrayList<String> list = new ArrayList<String>();
while (input.hasNext()) {
String name = input.next();
if (!list.contains(name)) {
list.add(name);
}
}
System.out.println("list = " + list);
Given the sample input file, this code produces the following output:
list = [Maria, Derek, Erica, Livia, Jack, Anita, Kendall, Jamie]
Notice that only 8 of the original 13 names appear in this list, because the various
duplicates have been eliminated.
Sometimes it is not enough to know that a value appears in the list. You may want
to know exactly where it occurs. For example, suppose you want to write a method to
replace the first occurrence of one word in an ArrayList<String> with another
word. You can call the set method to replace the value, but you have to know where
it appears in the list. You can find out the location of a value in the list by calling the
indexOf method.
 
Search WWH ::




Custom Search