Array List Example
Array List Example
java
1 import java.util.ArrayList;
2
3 /*
4 * ArrayList official documentation:
5 * https://goo.gl/RnWyvy
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 // list.add(newElement);
15 list.add(5); // Now the list contains --> [5]
16 list.add(7); // Now the list contains --> [5, 7]
17 list.add(1); // Now the list contains --> [5, 7, 1]
18
19 // To add new element to a specific position
20 // list.add(index, newElement);
21 // add 9 at position 0
22 list.add(0, 9); // Now the list contains --> [9, 5, 7, 1]
23 // add 3 at position 2
24 list.add(2, 3); // Now the list contains --> [9, 5, 3, 7, 1]
25
26 // To find the size of the list
27 System.out.println(list.size() + "\n");
28
29 // To access a specific element in the list
30 // list.get(index);
31 System.out.println(list.get(1) + "\n"); // Print the second element in the
list
32 System.out.println(list.get(4) + "\n"); // Print the fifth element in the
list
33
34 // Print the list
35 for (int i = 0; i < list.size(); ++i)
36 System.out.print(list.get(i) + " ");
37 System.out.println("\n");
38
39 // To Replaces an element at specified position in the list with new
element.
40 // list.set(index, newElement)
41 list.set(0, 4); // Change the first element to 4
42 list.set(2, 6); // Change the third element to 3
43 // Print the list
44 System.out.println(list + "\n");
45 // To Removes the element at the specified position in this list.
46 // list.remove(index)
47 list.remove(list.size() - 1); // remove the list element
48 System.out.println(list + "\n");
49 // To removes all of the elements from this list.
50 list.clear();
51 System.out.println(list.size() + "\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