File tree Expand file tree Collapse file tree 2 files changed +78
-0
lines changed
collections/arraylist/convert-arraylist-to-array Expand file tree Collapse file tree 2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .gaurav .ExProject .ArrayList ;
2+
3+ import java .util .ArrayList ;
4+
5+ /**
6+ * A java program to convert an ArrayList to array using
7+ * toArray method.
8+ *
9+ * toArray() method returns Object[]
10+ *
11+ * @author Gaurav Kukade at coderolls.com
12+ *
13+ */
14+ public class ArrayListToArray {
15+
16+ public static void main (String [] args ) {
17+ ArrayList <String > arrayList = new ArrayList <String >();
18+
19+ //adding elements to the arrayList
20+ arrayList .add ("Meta" );
21+ arrayList .add ("Apple" );
22+ arrayList .add ("Amazon" );
23+ arrayList .add ("Netflix" );
24+ arrayList .add ("Microsoft" );
25+ arrayList .add ("Google" );
26+
27+ System .out .println ("ArrayList: \n " + arrayList );
28+
29+ // convert ArrayList to array
30+ Object [] objects = arrayList .toArray ();
31+
32+ System .out .println ("\n Array:" );
33+
34+ //we will receive the object array, so iterate on it to print each element
35+ for (Object obj :objects ) {
36+ System .out .println (obj );
37+ }
38+ }
39+ }
Original file line number Diff line number Diff line change 1+ package com .gaurav .ExProject .ArrayList ;
2+
3+ import java .util .ArrayList ;
4+
5+ /**
6+ * A java program to convert an ArrayList to array using
7+ * toArray method.
8+ *
9+ * toArray(T[] a) method returns T[]
10+ *
11+ * @author Gaurav Kukade at coderolls.com
12+ *
13+ */
14+ public class ArrayListToArray2 {
15+
16+ public static void main (String [] args ) {
17+ ArrayList <String > arrayList = new ArrayList <String >();
18+
19+ //adding elements to the arrayList
20+ arrayList .add ("Meta" );
21+ arrayList .add ("Apple" );
22+ arrayList .add ("Amazon" );
23+ arrayList .add ("Netflix" );
24+ arrayList .add ("Microsoft" );
25+ arrayList .add ("Google" );
26+
27+ System .out .println ("ArrayList: \n " + arrayList );
28+
29+ // convert ArrayList to array
30+ // pass a new String array of the arrayList size as a param to toArray
31+ String [] elements = arrayList .toArray (new String [arrayList .size ()]);
32+
33+ System .out .println ("\n Array:" );
34+ //we will receive the string array, so iterate on it to print each element
35+ for (String str :elements ) {
36+ System .out .println (str );
37+ }
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments