ArrayListExample.
java
1 import [Link];
2
3 /*
4 * ArrayList official documentation:
5 * [Link]
6 */
7 public class ArrayListExample {
8
9 public static void main(String[] args) {
10 // ArrayList of integers - Initially it's empty
11 ArrayList<Integer> list = new ArrayList<>();
12
13 // To add new element to the end of the list
14 // [Link](newElement);
15 [Link](5); // Now the list contains --> [5]
16 [Link](7); // Now the list contains --> [5, 7]
17 [Link](1); // Now the list contains --> [5, 7, 1]
18
19 // To add new element to a specific position
20 // [Link](index, newElement);
21 // add 9 at position 0
22 [Link](0, 9); // Now the list contains --> [9, 5, 7, 1]
23 // add 3 at position 2
24 [Link](2, 3); // Now the list contains --> [9, 5, 3, 7, 1]
25
26 // To find the size of the list
27 [Link]([Link]() + "\n");
28
29 // To access a specific element in the list
30 // [Link](index);
31 [Link]([Link](1) + "\n"); // Print the second element in the
list
32 [Link]([Link](4) + "\n"); // Print the fifth element in the
list
33
34 // Print the list
35 for (int i = 0; i < [Link](); ++i)
36 [Link]([Link](i) + " ");
37 [Link]("\n");
38
39 // To Replaces an element at specified position in the list with new
element.
40 // [Link](index, newElement)
41 [Link](0, 4); // Change the first element to 4
42 [Link](2, 6); // Change the third element to 3
43 // Print the list
44 [Link](list + "\n");
45 // To Removes the element at the specified position in this list.
46 // [Link](index)
47 [Link]([Link]() - 1); // remove the list element
48 [Link](list + "\n");
49 // To removes all of the elements from this list.
50 [Link]();
51 [Link]([Link]() + "\n");
52 // ArrayList of double elements
53 // ArrayList<Double> list1 = new ArrayList<>();
54 // ArrayList of strings
55 // ArrayList<String> list2 = new ArrayList<>();
56 }
57 }
58
Page 1