55
66public class ArrayListExample {
77 public static void main (String args []) {
8- // create and initialize
8+ // create and initialize with ArrayList constructors
9+
910 List <Integer > lst1 = new ArrayList <>();
1011 lst1 .add (1 );
1112 lst1 .add (2 );
@@ -19,15 +20,27 @@ public static void main(String args[]) {
1920 List <Integer > lst4 = new ArrayList <>(Set .of (1 , 2 , 3 ));
2021 System .out .println (lst4 ); // [3, 2, 1]
2122
22- List <Integer > lst5 = Collections .emptyList ();
23+ // create and initialize with Arrays.asList
24+
25+ List <Integer > lst5 = Arrays .asList (1 , 2 , 3 );
26+
27+ // create and initialize with Collections factory methods
28+
29+ List <Integer > lst6 = Collections .emptyList ();
30+
31+ List <Integer > lst7 = Collections .singletonList (1 );
2332
24- List < Integer > lst6 = Collections . singletonList ( 1 );
33+ // create and initialize with Java 9+ List.of, List.copyOf
2534
26- List <Integer > lst7 = List .copyOf (lst6 );
35+ List <Integer > lst9 = List .of (1 , 2 , 3 );
36+ List <Integer > lst10 = List .copyOf (lst9 );
37+
38+ // iterate with Java 8+ forEach(Consumer)
2739
28- // iterate
2940 lst1 .forEach (System .out ::println );
3041
42+ // iterate with for loop
43+
3144 for (int ele : lst1 ) {
3245 System .out .printf ("%d " , ele );
3346 }
@@ -38,48 +51,58 @@ public static void main(String args[]) {
3851 }
3952 System .out .println ();
4053
54+ // iterate with iterator
55+
4156 Iterator <Integer > iter = lst1 .iterator ();
4257 while (iter .hasNext ()) {
4358 System .out .printf ("%d " , iter .next ());
4459 }
4560 System .out .println ();
4661
4762 // add elements into a list
63+
4864 lst1 .add (4 );
4965 lst1 .add (5 );
5066 lst1 .add (5 ); // add a duplicate element
5167 lst1 .add (null ); // add a null element
5268 System .out .println (lst1 ); // [1, 2, 3, 4, 5, 5, null]
5369
5470 // update an element at index
71+
5572 lst1 .set (0 , 10 );
5673
5774 // delete an element by index
75+
5876 lst1 .remove (1 );
5977
6078 // delete an element by value
61- lst1 .remove (null );
6279
80+ lst1 .remove (null );
6381
6482 // get an element by index
83+
6584 int i1 = lst1 .get (0 );
6685
6786 // check if an element existing
87+
6888 boolean isExist = lst1 .contains (3 );
6989
7090 // check the list size
7191 int size = lst1 .size ();
7292
7393 // check if the list is empty
94+
7495 boolean isEmpty = lst1 .isEmpty ();
7596
7697 // sort a list in ascending order
7798 // NullPointerException will be thrown if the list has null elements
99+
78100 lst1 .sort (Comparator .naturalOrder ());
79101 Collections .sort (lst1 );
80102 System .out .println (lst1 );
81103
82104 // sort a list in descending order
105+
83106 lst1 .sort (Comparator .reverseOrder ());
84107 Collections .sort (lst1 , Collections .reverseOrder ());
85108 System .out .println (lst1 );
0 commit comments