Как arraylist преобразовать в массив java
Перейти к содержимому

Как arraylist преобразовать в массив java

  • автор:

Java ArrayList.toArray()

Learn to convert ArrayList to an array using toArray() method. The toArray() method returns an array that contains all elements from the list – in sequence (from first to last element in the list).

1. ArrayList.toArray() API

The toArray() is an overloaded method:

  • The first method does not accept any argument and returns the Object[]. We must iterate the array to find the desired element and cast it to the desired type.
  • In second method, the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

After filling all array elements, if there is more space left in array then ‘null’ is populated in all those spare positions.

2. ArrayList toArray() Examples

2.1. Using toArray()

Java program to convert an ArrayList to Object[] and iterate through array content.

Как arraylist преобразовать в массив java

The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Now here we are given a List be it any LinkedList or ArrayList of strings, our motive is to convert this list to an array of strings in java using different methods.

Methods:

  1. Using get() method
  2. Using toArray() method
  3. Using Stream introduced in Java 8

Method 1: Using get() method

We can use the below list method to get all elements one by one and insert them into an array.

Return Type: The element at the specified index in the list.

How to Convert list to array in java

Before move further we should read what is Array and What is ArrayList in Java?
There may be many situations when we need to Convert list to array in java. There are many methods that allow us to convert ArrayList to array. In this post we will discuss how we convert ArrayList to array by use of different methods.

Convert list to array in java

Object[] toArray() method

The toArray() method is used to convert an ArrayList to Array in java. It returns an array that contains all the elements of the ArrayList. It retains the same order of elements as in the ArrayList. Let’s see how to convert list to array in java

accessModifier, This method is public so it can be accessed from any class.
return type, It returns an array of Object, Here Object is the class that is the topmost class in Java.
parameter, It doesn’t take any parameter.

Output: String Array:
JAVA
GOAL
LEARNING
WEBSITE
Integer Array:
123
456
789

Note: The toArray() method returns an array of type Object that is Object[].Here Object is topmost class so we need to typecast it. If we do not typecast, the compiler throws the compilation error. Let’s see the example of how it will work?

Output: Exception in thread “main” java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader ‘bootstrap’) at ArrayListExample.main(ArrayListExample.java:18)

A child class object can’t hold the object of Parent class. Here Object is parent class of all classes so we can’t convert it into Integer or String. To resolve this problem we can use toArray(T[] a) method.

toArray(T[] a) method

The toArray(T[] a) method is also used to convert an ArrayList to Array in java. This method takes a parameter of Array. If ​the size of the specified array is greater than or equal to the size of the ArrayList, then the toArray(T[] a) method fills the elements of the ArrayList in array. Otherwise, it creates a new array and filled up.

accessModifier, This method is public so it can be accessed from any class.
return type, it returns an array of T type. Where T is the object of Arrays which programmer wants to return.
parameter, It takes an object Array that programmer wants to fill
Exception, ArrayStoreException is thrown if any element in the list fails to be​ converted into the specified type.

Output: String Array:
JAVA
GOAL
LEARNING
WEBSITE
Integer Array:
123
456
789

get(int index) method

If you don’t want to use the toArray() method, you can use get() method and convert the ArrayList to Array.

Arraylist to Array Java

Both Arrays and ArrayLists in java are used to store multiple numbers of items of a single type. Arrays are of fixed size and cannot be resized once after the declaration, whereas ArrayList is a resizable array , each has its use-cases and benefits. Java provides the flexibility of conversion between them, let's explore how to convert an ArrayList to an array in java!

Scope

  • In this article, we'll learn how to convert ArrayList to an Array in java.
  • Have a walkthrough of different types of ways to achieve it.
  • And have a view of the syntax for different scenarios.

Introduction

Data structures provide an optimal way of storing the data, they are considered to be key components in operating systems and dynamic applications . Linear data structures are one of the most used data structures among them. Arrays in java inherit Object class and are objects of a dynamically generated class, and ArrayList in java is a class from the java collection framework available in java.util library. Although opting for a data structure depends on the use case, there will be cases where we've to switch to other data structures. In our case we are looking to convert an ArrayList to Array in Java, but how to do that?

How To Convert ArrayList To Array In Java ?

Elements in ArrayLists are objects of wrapper classes like Integer , Double , Boolean , Short , etc which can store one primitive value. Whereas elements in arrays are of primitive types. Examples are int , double , byte , short , etc. Java provides mechanisms like autoboxing (converting a primitive value to a corresponding object of wrapper class) and unboxing (converting an object of a wrapper class to a corresponding primitive type) to change the data type from primitives to objects and vice-versa. A trivial way of converting an ArrayList to an Array is by declaring an array of the given size and keeping adding the numbers sequentially. But, is this the only way?

ArrayList To Array Conversion In Java

Let's walk through 3 different ways of conversion

1. Manual conversion using the get() method

As discussed earlier, we'll declare an array of the given size, then iterate over each number and add it to the array. And here's the code to do that in java

Let's have a walkthrough of the code. Initially, we're importing the List interface and ArrayList class from the java util library then declared an ArrayList of integers . We've added a few elements to the ArrayList.

To convert it to an array, we've created an array of the given size. We've created one primitive array , and an object array to demonstrate the unboxing concept. While appending elements to ObjectArr[], elements are stored as Integer class objects which is a straight operation since the get() method returns an object. Whereas appending in PrimitiveArr[] is not a direct operation, java performs unboxing which converts the object to a primitive type, and then it is stored in the array.

Once we add all the elements to the array, we're printing the elements of the newly created arrays.

Output

The space complexity of this code will be O ( n ) O(n) O ( n ) since we are declaring a new array of the given size n .

Here we've converted an ArrayList to Array in Java but the code seems to be a little long right?

2. Object[] toArray() method in java

This way of converting an ArrayList to Array in Java uses the toArray() method from the java List interface and returns an array of type Object. It will convert the list to an array without disturbing the sequence of the elements.

And here's the code to do that in java

Let's have a walkthrough of the code. We've declared an array of type Object and assigned the value returned by the toArray() method. This will dynamically create an array of the required size and append the elements to it.

We can also pass an object array as the parameter, this method signature will be useful if we already have an array of size which is larger enough to store the elements such that the elements of the list are stored in the array which is passed as parameter. The size of the array need not be exact but should be large enough, else the array remains unchanged.

Then we’re printing the elements of the newly created arrays.

Output

The space complexity of this code will not be affected if elements are appended to the parameter array, else O ( n ) O(n) O ( n ) since a new array will be created.

Remember if the elements are to be stored in a primitive int[] array or object Integer[] array, then each element has to be typecasted and then stored.

Directly assigning the Object[] array to an Integer[] array will throw an error in java. And here's the java code to demonstrate that

3. T[] toArray(T[] arr) method in java

This way of converting an ArrayList to Array in Java uses the toArray() method and returns an array whose type is the same as the parameter passed to the array. The parameter array will not only decide the type of returned array but also stores the elements in it if the array is large enough. If the parameter array is smaller than required then a new array will be returned.

And here's the code to do that in java

Let's have a walkthrough of the code. We've declared an Integer array and an Object array of the required size. Then passed it to the toArray() method, since the size of the array is large enough the elements are added to the same array. The code will work fine with both the Integer array and Object array because Integer and Object fall under the supertype of the elements in ArrayList.

Then we’re printing the elements of the newly created arrays.

Output

Remember the type of parameter array has to be the supertype of the elements in the ArrayList i.e. if the elements in ArrayList are of Integer type, then the converted array can be of type Integer or Object . Else the program will throw an error.

Here's the java code to demonstrate that

Conclusion

Arrays are of fixed size and can store elements of primitive types .

ArrayLists are resizable arrays and can store elements of type wrapper class objects.

Java provides the flexibility of converting ArrayLists to Array and vice versa.

There are three ways of conversion — manual conversion using get() method, using Object[] toArray() method, using T[] toArray(T[] arr) method.

In conclusion, on which way to opt for converting an ArrayList to Array in Java, we can go for

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *