Can we cast ArrayList to list in Java?

import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages= new ArrayList<>(); // Add elements in the array list languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); System.out.println("ArrayList: " + languages); // convert the arraylist into a string String arraylist = languages.toString(); System.out.println("String: " + arraylist); } }

Output

ArrayList: [Java, Python, JavaScript] String: [Java, Python, JavaScript]

In the above example, we have created an arraylist named languages. Notice the line,

languages.toString();

Here, the toString() method converts arraylist into a string. The entire arraylist is converted as a single string.

Note: We can also convert the arraylist into a string array. To learn more, visit Java ArrayList to Array Conversion.

Example 2: Convert ArrayList to String Using join()

import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages= new ArrayList<>(); // Add elements in the array list languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); System.out.println("ArrayList: " + languages); // convert the arraylist into a string String arraylist = String.join(", ", languages); System.out.println("String: " + arraylist); } }

Output

ArrayList: [Java, Python, JavaScript] String: Java, Python, JavaScript

In the above example, we have used the join() method of the String class to convert the arraylist into a string. To learn more, visit Java String join().

Example 3: Convert a String to ArrayList

import java.util.ArrayList; import java.util.Arrays; class Main { public static void main(String[] args) { // create a string String str = "Java, JavaScript, Python"; System.out.println("String: " + str); // convert the string into an array String[] arr = str.split(","); // create an arraylist from the string ArrayList<String> languages = new ArrayList<>(Arrays.asList(arr)); System.out.println("ArrayList: " + languages); } }

Output

String: Java, JavaScript, Python ArrayList: [Java, JavaScript, Python]

In the above example, we have created a string named str. We have used the split() method to convert the given string into an array. To learn more about splitting a string, visit Java String split().

Notice the expression,

Arrays.asList(arr)

The asList() method converts the string array into an arraylist.

Following methods can be used for converting ArrayList to Array:
 

Method 1: Using Object[] toArray() method

Syntax: 
 



public Object[] toArray()
  • It is specified by toArray in interface Collection and interface List
  • It overrides toArray in class AbstractCollection
  • It returns an array containing all of the elements in this list in the correct order.

import java.util.ArrayList;

    public static void main(String[] args)

        List<Integer> al = new ArrayList<Integer>();

        Object[] objects = al.toArray();

        for (Object obj : objects)

            System.out.print(obj + " ");

Note: toArray() method returns an array of type Object(Object[]). We need to typecast it to Integer before using as Integer objects. If we do not typecast, we get compilation error. Consider the following example: 
 

import java.util.ArrayList;

    public static void main(String[] args)

        List<Integer> al = new ArrayList<Integer>();

        Integer[] objects = al.toArray();

        for (Integer obj : objects)

Output: 

19: error: incompatible types: Object[] cannot be converted to Integer[] Integer[] objects = al.toArray(); ^ 1 error

It is therefore recommended to create an array into which elements of List need to be stored and pass it as an argument in toArray() method to store elements if it is big enough. Otherwise a new array of the same type is allocated for this purpose.
 

Method 2: Using T[] toArray(T[] a)

// Converts a list into an array arr[] and returns same. // If arr[] is not big enough, then a new array of same // type is allocated for this purpose. // T represents generic. public T[] toArray(T[] arr)

Note that the there is an array parameter and array return value. The main purpose of passed array is to tell the type of array. The returned array is of same type as passed array. 
 

  • If the passed array has enough space, then elements are stored in this array itself.
  • If the passed array doesn’t have enough space, a new array is created with same type and size of given list.
  • If the passed array has more space, the array is first filled with list elements, then null values are filled.

It throws ArrayStoreException if the runtime type of a is not a supertype of the runtime type of every element in this list.
 

import java.util.ArrayList;

    public static void main(String[] args)

        List<Integer> al = new ArrayList<Integer>();

        Integer[] arr = new Integer[al.size()];

            System.out.print(x + " ");

Note : If the specified array is null then it will throw NullpointerException. See this for example.
 

Method 3: Manual method to convert ArrayList using get() method

We can use this method if we don’t want to use java in built toArray() method. This is a manual method of copying all the ArrayList elements to the String Array[]. 

// Returns the element at the specified index in the list. public E get(int index)

import java.util.ArrayList;

    public static void main(String[] args)

        List<Integer> al = new ArrayList<Integer>();

        Integer[] arr = new Integer[al.size()];

        for (int i = 0; i < al.size(); i++)

            System.out.print(x + " ");

Method 4: Using streams API of collections in java 8 to convert to array of primitive int type

We can use this streams() method of list and mapToInt() to convert ArrayList<Integer> to array of primitive data type int

int[] arr = list.stream().mapToInt(i -> i).toArray();

import java.util.ArrayList;

    public static void main(String[] args)

        List<Integer> al = new ArrayList<Integer>();

        int[] arr = al.stream().mapToInt(i -> i).toArray();

            System.out.print(x + " ");

Reference: 
//docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray()
This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Practice Tags :

Video liên quan

Chủ đề