-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJavaArrayList.java
More file actions
75 lines (59 loc) · 1.77 KB
/
JavaArrayList.java
File metadata and controls
75 lines (59 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
public class JavaArrayList {
public static void printArray(final ArrayList<String> words) {
System.out.print('[');
boolean first = true;
for (final String word : words) {
if (first) {
first = false;
} else {
System.out.print(", ");
}
System.out.print(word);
}
System.out.println(']');
}
public static void main(String[] args) {
ArrayList<String> words1 = new ArrayList<>(
Arrays.asList("the", "frogurt", "is", "also", "cursed")
);
printArray(words1);
ArrayList<String> words2 = new ArrayList<>(words1);
printArray(words2);
ArrayList<String> words3 = new ArrayList<>(Collections.nCopies(5, "Mo"));
printArray(words3);
System.out.print("\n foreach ArrayList\n");
for (final String word : words1) {
System.out.println(": " + word);
}
System.out.print("\n for-loop ArrayList\n");
for (Iterator<String> iter = words1.iterator(); iter.hasNext();) {
System.out.println(": " + iter.next());
}
System.out.print("\n ArrayList.get(0)\n");
System.out.println(words1.get(0));
System.out.print("\n add(index, str)\n");
words1.add(0, "First");
printArray(words1);
words1.add(1, "appended");
printArray(words1);
System.out.print("\n add(str) to last element\n");
words1.add("last");
printArray(words1);
System.out.print("\n remove()\n");
words1.remove(0);
printArray(words1);
words1.subList(1, 3).clear();
printArray(words1);
System.out.print("\n swap()\n");
Collections.swap(words1, 0, 1);
printArray(words1);
Collections.swap(words1, 0, 1);
printArray(words1);
System.out.print("\n indexOf()\n");
System.out.println("index: " + words1.indexOf("also"));
}
}