Java Reference
In-Depth Information
Chapter 10
1. 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.
2. 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.
3. list.add(3, "dark");
list.add(4, "and");
4. list.set(1, "IS");
5. 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
}
}
6. ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
numbers.add(2 * i);
}
7. 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;
}
8. System.out.println(list.contains("IS"));
9. System.out.println(list.indexOf("stormy"));
System.out.println(list.indexOf("dark"));
 
Search WWH ::




Custom Search