- How to Convert Array to ArrayList in Java?
- Related posts:
- How to Convert an array to ArrayList in java
- Method 1: Conversion using Arrays.asList()
- Method 2: Conversion using Collections.addAll() method
- Method 3: Convert Array to ArrayList manually
- Top Related Articles:
- About the Author
- Comments
- Java – Convert Array to ArrayList
- 1. Java 8 Stream
- 2. Java 9 – List.of()
- References
How to Convert Array to ArrayList in Java?
This article analyzes answers for a top-voted questions on Stack Overflow. The person who asked this question got a lot of reputation points, which could grant him permissions to do a lot of things on Stack Overflow. This does not make sense to me, but let’s take a look at the question first.
The question is «how to convert the following array to an ArrayList?».
Element[] array = {new Element(1),new Element(2),new Element(3)};
1. Most popular and accepted answer
The most popular and the accepted answer is the following:
ArrayListElement> arrayList = new ArrayListElement>(Arrays.asList(array));
ArrayList arrayList = new ArrayList(Arrays.asList(array));
First, let’s take a look at the Java Doc for the constructor method of ArrayList.
ArrayList(Collection c) : Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
So what the constructor does is the following:
1. Convert the collection c to an array
2. Copy the array to ArrayList’s own back array called «elementData»
Here is the source code of Contructor of ArrayList.
public ArrayList(Collection extends E> c) { elementData = c.toArray(); size = elementData.length; if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
public ArrayList(Collection c)
2. Next popular answer
The next popular answer is:
ListElement> list = Arrays.asList(array);
List list = Arrays.asList(array);
It is not the best, because the size of the list returned from asList() is fixed. Actually the list returned is not java.util.ArrayList , but a private static class defined inside java.util.Arrays . We know ArrayList is essentially implemented as an array, and the list returned from asList() is a fixed-size list backed by the original array. In this way, if add or remove elements from the returned list, an UnsupportedOperationException will be thrown.
Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList at collection.ConvertArray.main(ConvertArray.java:22)
3. Another Solution
This solution is from Otto’s comment below.
Element[] array = {new Element(1), new Element(2)}; Listelement> list = new ArrayListelement>(array.length); Collections.addAll(list, array);
Element[] array = ; List list = new ArrayList(array.length); Collections.addAll(list, array);
4. Indications of the question
The problem is not hard, but interesting. Every Java programmer knows ArrayList, but it’s easy to make such a mistake. I guess that is why this question is so popular. If a similar question asked about a Java library in a specific domain, it would be less likely to become so popular.
There are several answers that provide the same solution. This is also true for a lot of other questions on Stack Overflow, I guess people just don’t care what others say if they would like to answer a question!
Related posts:
If you want someone to read your code, please put the code inside
and
tags. For example:
Thanks For sharing such good article . I am sharing one good article on the same topic but have different ways visit Array To ArrayList
will this conversion
ArrayList arrayList = new ArrayList(Arrays.asList(array)); of array to arraylist change sequence or not
With Java 8 stream there is one other way –
If I have an Array of cities Say cityArray, it can be converted to List this way – List cityList = Stream.of(cityArray).collect(Collectors.toList()); Read other options here – http://netjs.blogspot.com/2015/09/how-to-convert-array-to-arraylist-in-java.html
i have one question.how can link array names with string names like i will declare an array a1 and if any where i compare a string “a1” then it should link with array a1 and i should be able to manupulate array a1 values using this string a1. is it possible to do like that
I take back what I said about Hibernate not being able to handle Arrays$ArrayList. I was getting an exception before, but now it is working. Maybe it won’t work if there’s autoboxing involved.
Thanks for adding the solution to the post.
I’d also like to add that solution 2 has the best performance, but does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList and that might fail depending on the expected implementation. Hibernate/JPA’s Query.setParameter(), for example, can’t handle that List type.
Hi. The most popular answer works, but it is not efficient. From what I have tested, this solution offers a better performance:
Element[] array = ;
List list = new ArrayList(array.length);
Collections.addAll(list, array);
I looked over your post again and saw that I misunderstood you. Yes, the new ArrayList is sized to exactly fit the original array, so if someone adds an additional element, the ArrayList is resized. Seems reasonable. How else would you expect it to work?
Came here from the DZone posting. What version of Java are you basing this on? I took a look at the source for Array(Collection) and Arrays.asList(T…) in Java 6 and 7 and it looks like they use very direct, efficient approaches: public ArrayList(Collection c) <
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
> In Arrays:
public static List asList(T… a) <
return new ArrayList(a);
> ArrayList(E[] array) <
if (array==null)
throw new NullPointerException();
a = array;
>
How to Convert an array to ArrayList in java
In the last tutorial, you learned how to convert an ArrayList to Array in Java. In this guide, you will learn how to convert an array to ArrayList.
Method 1: Conversion using Arrays.asList()
ArrayList arraylist= new ArrayList(Arrays.asList(arrayname));
Example:
In this example, we are using Arrays.asList() method to convert an Array to ArrayList.
Here, we have an array cityNames with four elements. We have converted this array to an ArrayList cityList . After conversion, this arraylist has four elements, we have added two more elements to it using add() method.
In the end of the program, we are printing the elements of the ArrayList, which displays 6 elements, four elements that were added to arraylist from array and 2 new elements that are added using add() method.
import java.util.*; public class JavaExample < public static void main(String[] args) < // Array declaration and initialization String cityNames[]=; // Array to ArrayList conversion ArrayList cityList= new ArrayList(Arrays.asList(cityNames)); // Adding new elements to the list after conversion cityList.add("Chennai"); cityList.add("Delhi"); //print ArrayList elements using advanced for loop for (String str: cityList) < System.out.println(str); >> >
Agra Mysore Chandigarh Bhopal Chennai Delhi
Method 2: Conversion using Collections.addAll() method
Collections.addAll() method adds all the array elements to the specified collection. We can call the Collections.addAll method as shown below. It works just like Arrays.asList() method however, it is much faster. Conversion using Collections.addAll() method gives better performance compared to asList() method.
String array[]=; ArrayList arraylist = new ArrayList(); Collections.addAll(arraylist, array);
Collections.addAll(arraylist, new Item(1), new Item(2), new Item(3), new Item(4));
import java.util.*; public class JavaExample < public static void main(String[] args) < // Array declaration and initialization*/ String array[]=; //ArrayList declaration ArrayList arraylist= new ArrayList(); // conversion using addAll() Collections.addAll(arraylist, array); //Adding new elements to the converted List arraylist.add("String1"); arraylist.add("String2"); //print ArrayList for (String str: arraylist) < System.out.println(str); >> >
Hi Hello Howdy Bye String1 String2
Method 3: Convert Array to ArrayList manually
This program demonstrates how to convert an Array to ArrayList without using any predefined method such as asList() and addAll() .
The logic of this program is pretty simple, we are iterating the array using for loop and adding the element to the ArrayList on every iteration of the loop. This means, in the first iteration, the first element of the array is added to the ArrayList, in the second iteration second element gets added and so on.
To read the whole array, we are using arr.length property. The array.length property returns the number of elements in the array. In the following example, since the array contains four elements, this will return 4. Thus we can say that the for loop runs from i=0 to i
In the end, we are displaying ArrayList elements using advanced for loop.
import java.util.*; public class JavaExample < public static void main(String[] args) < //ArrayList declaration ArrayListarrayList= new ArrayList(); //Initializing Array String array[] = ; /* array.length returns the number of * elements present in array*/ for(int i =0;i//print ArrayList content for(String str: arrayList) < System.out.println(str); >> >
Recommended Articles:
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
In Method 2 ,
can’t we use this method to convert array to arraylist :
arraylist.addAll(array); as we have used it earlier for list :
arraylist.addAll(list);
Hello,
The method to convert an array to ArrayList using Arrays.asList() works well for any String array, but not with Integer type arrays. Please help.
Thanks
If you are using the array as “int[] obj=new int[x];” then it will not work because the array list can be created for the Integer class not the int class so it will return a type mismatch error. so take the array as Integer[] obj=new Integer[x];
Java – Convert Array to ArrayList
The Arrays.asList returns a fixed or unmodifiable list, if we modify the list, UnsupportedOperationException will be thrown.
List list = Arrays.asList(str); // unmodifiable list list.add("D"); // java.lang.UnsupportedOperationException List list2 = new ArrayList<>(Arrays.asList(str)); // modifiable list list2.add("D"); // ok
1. Java 8 Stream
package com.mkyong; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ArrayExample2 < public static void main(String[] args) < String[] str = ; ArrayList list1 = Stream.of(str).collect(Collectors.toCollection(ArrayList::new)); list1.add("D"); list1.forEach(x -> System.out.println(x)); List list2 = Stream.of(str).collect(Collectors.toList()); list2.add("D"); list2.forEach(x -> System.out.println(x)); > >
2. Java 9 – List.of()
P.S List.of returns fixed or unmodifiable list
package com.mkyong; import java.util.ArrayList; import java.util.List; public class ArrayExample3 < public static void main(String[] args) < String[] str = ; // Java 9 List list = new ArrayList<>(List.of("A", "B", "C")); list.add("D"); list.forEach(x -> System.out.println(x)); > >
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.