[Java] Convert array to ArrayList * Caution

How to convert an array to ArrayList and precautions / pitfalls

I will show you how to convert an array to an ArrayList. There are pitfalls that you will definitely fall in love with, so read on to the end!

ListToArray.java


String[] array ={"A","B","C"};
List<String> list =  Arrays.asList(array);
System.out.println("Array= " + Arrays.toString(array));
System.out.println("List = " + list.toString());

result

Array= [A, B, C]
List = [A, B, C]

did it! It's easy.

... but

Try adding an element

ListToArray.java


//Omission
List<String> list =  Arrays.asList(array);
list.add("D"); //Add D!

result

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at codeSample.ListToArray.main(ListToArray.java:13)

Get an error

why

Try to get the class to return

ListToArray.java


//Omission
List<String> list =  Arrays.asList(array);
ArrayList<String> arrayList = new ArrayList<String>();
System.out.println("Regular ArrayList= " + arrayList.getClass());
System.out.println("Conversion from array= " + list.getClass());

result

Regular ArrayList= class java.util.ArrayList
Conversion from array= class java.util.Arrays$ArrayList

Hmm, something different!

Try deep digging

java:java.util.Arrays.class


//Omission
public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a; //←←← is final!

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);    //Reference copy (additional note)
        }

        @Override
        public int size() {
            return a.length;
        }
//Omission
    }

It was returning a simplified version of ArrayList defined in the inner class of the Arrays class!

java:java.util.AbstractList.class


public boolean add(E e) {
    add(size(), e);
    return true;
}
//Omission
public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

Fix

ListToArray.java


//Omission
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(array));
arrayList.add("D");
System.out.println("Array= " + Arrays.toString(array));
System.out.println("List = " + arrayList.toString());

Create a new ArrayList area and convert it. (Addition)

result

Array= [A, B, C]
List = [A, B, C, D]

Arrays.asList () just converts the type, and the referenced memory area remains the same. (Addition)

Recommended Posts

[Java] Convert array to ArrayList * Caution
[Java] Convert ArrayList to array
Convert Java Powerpoint to XPS
How to convert Java radix
How to initialize Java array
How to convert a file to a byte array in Java
Convert alphabet to 26 base + array length
[Java] array
Java array
[Java] I want to convert a byte array to a hexadecimal number
java (array)
Java array
[Java] Array
Java basic learning content 2 (array / ArrayList)
[Java] Convert 1-to-N List to Map
Java array
[Java] Difference between array and ArrayList
[Java] How to use List [ArrayList]
For Java beginners: List, Map, Iterator / Array ... How to convert?
Convert 2D array to csv format with Java 8 Stream API
[Java] Conversion from array to List
[Java] Array
How to make a Java array
Convert Swift 2D array to C 2D array
Convert all Android apps (Java) to Kotlin
Convert from java UTC time to JST time
[Java] Convert Object type null to String type
Convert SVG files to PNG files in Java
Convert an array of strings to numbers
java array variable
[Java] Array notes
[Java] Introduction to Java
Introduction to java
[Java] From two Lists to one array list
Convert a string to a character-by-character array with swift
How to convert a solidity contract to a Java contract class
Convert Java nested beans to aaa.bbb [0] .ccc format
Two-dimensional array by just starting to study Java
Launch Docker from Java to convert Office documents to PDF
<java> Read Zip file and convert directly to string
[Java] Convert PDF version
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
Convert Java enum enums and JSON to and from Jackson
Sample code to convert List to List <String> in Java Stream
Convert the array of errors.full_messages to characters and output
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2
[Java] Connect to MySQL
About Java Array List
Kotlin's improvements to Java
Java applications convert Word (DOC / DOCX) documents to PDF
[Java ~ Array ~] Study memo 4
From Java to Ruby !!
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 1
How to convert A to a and a to A using AND and OR in Java
Introduction to java command
Gzip-compress byte array in Java and output to file
[Java] What is ArrayList?
[Java] How to convert a character string from String type to byte type
How to store a string from ArrayList to String in Java (Personal)
I tried to convert a string to a LocalDate type in Java
Convert an array that may be null to a stream