Wednesday, December 14, 2022

How to create an ArrayList from Array in Java? Arrays.asList() Example Tutorial

One of the common problems faced by junior and less experienced Java developers is converting an array to ArrayList e.g. they are getting an array from somewhere in their code and then want to create an ArrayList out of that so that they can add more elements and use other library methods which operate with ArrayList or List. The simplest way to convert an array to ArrayList is by using the Arrays.asList() method, which acts as a bridge between Collection classes and array data structure. This method returns a List that contains elements from an array. 

However, you need to be careful while using this method becuase the list returned by this method is not an ArrayList, but just a List implementation that is fixed size i.e. you cannot add new elements into the list. If you call the add() or remove() method on the list returned by Arrays.asList() method, the code will throw UnSupportedOperationException as shown in our example below. 

Why do you need to convert the array to ArrayList? Well, there are multiple reasons but the most important reason I know is to add more objects or values. 

An array is a static data structure, which means you cannot add more values into it once it is filled, but ArrayList is a dynamic data structure, which can grow automatically if filled. This means you can add as many elements as you want without worrying about the size of the ArrayList (of course until heap memory is exhausted). 

Another reason to convert an array to ArrayList is to take advantage of the Java Collection framework, which provides several convenient methods for sorting and searching through ArrayList. You can also pass an ArrayList to a method which is accepting a List or Collection interface, this makes it easy to pass around your data between different parts of code. 





How to convert an Array to ArrayList in Java

As I told in the first paragraph, you can convert an array to ArrayList in Java by using the Arrays.asList() method. This is a generic method that allows you to convert an array of objects to the corresponding ArrayList

Though you should remember that this method doesn't return an ArrayList, instead it gives you an implementation of java.util.List interface. Also, the resultant list is a fixed size list, which means you cannot add new objects and remove old objects, though you can change/update existing objects.

 It is also backed by the array and write-through, which means any change in the array will reflect in the list and vice-versa. 

In order to convert the returned List to ArrayList, you can use the copy constructor of the Collection interface, which is also available to the List and ArrayList class as shown in this article. This way, you get a proper ArrayList object, where you can add new elements and remove existing elements depending upon your requirement. 


How to create an ArrayList from Array in Java? Arrays.asList() Example Tutorial



Java program to create ArrayList from array

Here is our complete Java program to convert an Array to List in Java:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/*
* Java Program to sort an ArrayList
*/

public class Main {


    public static void main(String[] args) throws Exception {

        // a simple String array
        String[] names = new String[] {
            "Java",
            "C++",
            "JavaScript",
            "Python"
        };


        // converting an array to a List
        List < String > listOfNames = Arrays.asList(names);

        // the returned list is not an ArrayList
        if (listOfNames instanceof ArrayList) {
            System.out.println("The returned list is instance of an ArrayList");
        }


        // the returned list is not read only
        System.out.println("list before update: " + listOfNames);
        listOfNames.set(0, "Java 8");
        System.out.println("list after update: " + listOfNames);


        // list if backed by array, any change in array will reflect in list
        names[0] = "R";
        names[1] = "C#";
        System.out.println("list after changing array: " + listOfNames);


        // the returned list is a fixed size list
        listOfNames.add("Ruby");
        listOfNames.remove("JavaScript");


        // The right way to create an ArrayList from array 
        String[] loans = new String[] {
            "home loan",
            "personal loan",
            "gold loan"
        };

        ArrayList < String > loans = new ArrayList < > (Arrays.asList(loans));

    }

}



Output
list before update: [Java, C++, JavaScript, Python]
list after update: [Java 8, C++, JavaScript, Python]
list after changing array: [R, C#, JavaScript, Python]

Exception in thread "main"
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java: 148)
at java.util.AbstractList.add(AbstractList.java: 108)
at Main.main(Main.java: 66)

You can see from the output that the list returned by Arrays.asList() is not an ArrayList, that's why the instanceof check doesn't pass. 




You can also see that the list is not read-only or unmodifiable because we can replace the existing elements, as we replaced "Java" to "Java 8" at index 0. Another thing that we have verified in the code is that the list is backed by an array, any change in the array will reflect in the list as well. 

We have changed the value at index 0 and 1 i.e. we replaced "Java 8" to "R" and "C++" to "C#" in the array and when we printed the list, it shows that content has been changed at respective indices. 

The last thing which is verified from the code is that the list returned from the Arrays.asList() method is a fixed-size list, which means you cannot add/remove elements. Tring to add or remove will result in java.lang.UnsupportedOperationException as shown by the stack trace of our program. 

So far, in our example, we have converted an array of String objects to ArrayList of String objects, but you can also convert an array of Integer objects to ArrayList of Integer as well as an array of user-defined objects to ArrayList of the user-defined object as shown below:

/*
* Java Program to create an ArrayList of objects from array of user defined objects
*/

public class Main {

    public static void main(String[] args) throws Exception {

        // converting an array of Integer to arrayList of Integer
        Integer[] primes = new Integer[] {
            2,
            3,
            5,
            7,
            11,
            13,
            17
        };

        ArrayList < Integer > listOfPrimes = new ArrayList<>(Arrays.asList(primes));

        System.out.println("Integer array: " + Arrays.toString(primes));
        System.out.println("ArrayList of Integer from array: " + listOfPrimes);

        Course[] courses = new Course[3];
        courses[0] = new Course("REST with Spring", 99);
        courses[1] = new Course("Learn Spring Security", 110);
        courses[2] = new Course("Introduction to Spring MVC4", 12);

        ArrayList <Course> listOfSpringCourses 
        = new ArrayList<> (Arrays.asList(courses));

        System.out.println("array of courses: " + Arrays.toString(courses));
        System.out.println("list of courses from array: " + listOfSpringCourses);

    }



}



class Course {
    String title;
    long fee;

    public Course(String title, long fee) {
        this.title = title;
        this.fee = fee;
    }

    public String title() {
        return title;
    }

    public long fee() {
        return fee;
    }


    @Override
    public String toString() {
        return String.format(title + "@ " + fee);
    }

}



Output
Integer array: [2, 3, 5, 7, 11, 13, 17]
ArrayList of Integer from array: [2, 3, 5, 7, 11, 13, 17]
an array of courses: [REST with Spring @ 99, 
Learn Spring Security @ 110, 
Introduction to Spring MVC4 @ 12]
list of courses from the array: [REST with Spring @ 99, 
Learn Spring Security @ 110, 
Introduction to Spring MVC4 @ 12]


You can see it's easy to create an ArrayList of Integer from an array of Integer objects and you can also convert an array of user-defined custom objects to ArrayList of custom objects. However, it's not that easy to convert an array of int primitive values to ArrayList of Integer. If you try, it will pose some problems because the Arrays.asList() method cannot convert int[] to Integer[] automatically. We'll see how to solve that problem in our next article. 





Important points about Arrays.asList() method

Now that you know how to convert an array to ArrayList or how to create an ArrayList from the array, it's time to revise some important points about the Array.asList() method which acts as a bridge between Collection classes and array data structure. These points are very important and you must read them before using Arrays.asList() in your code.

1) The Arrays.asList() method is used to convert an Array to ArrayList in Java. 

2) You can also use Array.asList() with variable arguments, which means you can pass objects directly to these methods to create a List e.g. to create a List of three String objects you can write code like this:

List<String> cards = Arrays.asList("ATM card", "Debit card", "Credit card");

This is a convenient way to create a fixed-size list in one line. 

3) This method returns a fixed-size list, which means you cannot add or remove elements from this list, though you can change the value of existing elements by using the set() method. This means, the list is fixed size but not read-only or unmodifiable which doesn't allow you to add, update, or remove elements.

4) The Arrays.asList() method doesn't return an ArrayList, instead, it just returns an implementation of the List interface, which may vary between Java versions. Though, you can convert the list returned by this method to an ArrayList using the following example:

ArrayList<String> loans = new ArrayList<>(Arrays.asList("home loan",
                          "personal loan", "gold loan");

This code uses the copy constructor of the Collection interface to copy elements from one list to another list.

5) The list returned by the Arrays.asList() is backed by the specified array. This means any change in the list or array is reflected in the array as well. 

6) This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray. 

7) The list returned by Arrays.asList() is both serializable and implements RandomAccess. 


That's all about how to create an ArrayList from an array in Java. Though there are more complex ways to create an ArrayList out  of an array e.g. manually copying each element using a for loop, this is the easiest way to do the task. You won't find anything simpler than Arrays.asList(). It also offers a convenient way to create ArrayList from values using variable arguments. 

However, you need to remember that the list returned by Arrays.asList() is not an ArrayList but just another List implementation. It is also a fixed-size list which means you cannot add or remove elements and it's backed by an array, which means any change in the array will reflect in the list as well.

The best way is to create an ArrayList by copying elements from the list returned by Arrays.asList(), this way you get a full-fledged ArrayList where you can also add more elements. 

Other ArrayList tutorials for Java Programmers

  • Difference between an Array and ArrayList in Java? (answer)
  • How to reverse an ArrayList in Java? (example)
  • Top 5 Courses to learn Hibernate for Java developers (courses)
  • How to loop through an ArrayList in Java? (tutorial)
  • How to synchronize an ArrayList in Java? (read)
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • 10 Courses to learn Java Programming for beginners (courses)
  • How to create and initialize ArrayList in the same line? (example)
  • 10 Free Spring Boot Courses for Java developers (courses)
  • Difference between ArrayList and HashSet in Java? (answer)
  • 10 Free Courses to learn Spring Framework (courses)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Difference between ArrayList and HashMap in Java? (answer)
  • Difference between ArrayList and Vector in Java? (answer)
  • How to sort an ArrayList in descending order in Java? (read)
  • How to get a sublist from ArrayList in Java? (example)
  • How to convert CSV String to ArrayList in Java? (tutorial)
  • How to remove objects from ArrayList in Java (example)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions, suggestions, or any doubt related to the concepts explained in this article, then please drop a comment and I'll try to answer your question. 

1 comment:

  1. You can also use Stream to create an array from ArrayList in Java post JDK 8 versions

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.