[Java] Points to note with Arrays.asList ()

Introduction

When I used Java for a long time, I got stuck in Arrays.asList () a little, so I will write down the notes of Arrays.asList () as a memorandum.

What is Arrays.asList ()

String[] words = {"abc","def","ghi"};
List<String> list = Arrays.asList(words);

Notes on Arrays.asList ()

1. Fixed list length of return values

Returns a fixed size list that works with the specified array.

In [Java API](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Arrays.html#asList-T ...-), write as above. It has been done. This means that the length of the list is fixed, even if the return value of the asList method is a list.

For example, if you try to change the number of elements with the add method or remove method for the return value of the asList method, a compile error will not occur, but at runtime [java.lang.UnsupportedOperationException](https://docs.oracle. com / javase / jp / 8 / docs / api / java / lang / UnsupportedOperationException.html) will occur.

This point is also written in the API, so if you check the API properly, you can clear it without any problems.

//Adding elements to a fixed length list
static void add() {
	List<Integer> fixedSizeList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
	//UnsupportedOperationException occurs at runtime.
	fixedSizeList.add(11);
}

//Deleting elements for fixed-length lists
static void remove() {
	List<Integer> fixedSizeList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
	//UnsupportedOperationException occurs at runtime.
	fixedSizeList.remove(5);
}

The problem of "list length is fixed" can be avoided by "specify the list generated by the asList method in the constructor of ArrayList" as shown below.

Conversion from list to array can be done in one shot by using List # toArray (), but conversion from array to variable length list seems to be inevitably two steps.

// Arrays.asList()Convert the list created in step 3 to a variable length (mutable) list.
static void add2() {
	List<Integer> fixedSizeList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
	List<Integer> list = new ArrayList<>(fixedSizeList);
	//No error at run time.
	list.add(11);
}

2. If you specify a primitive type array as an argument, it behaves unexpectedly.

If you specify an array of primitive type in the argument of Arrays.asList (), the return value will not be List <wrapper class type>. For example, if you specify int [] as an argument of Arrays.asList (), the return value will be List <int []>.

This wasn't written in the API at all, so I was worried that it wouldn't compile at first, but as a result, I was relieved to find that it worked as specified.

It seems that there is a method such as "specify an array of wrapper class type as an argument" to avoid this problem, but it seems strange to bother to convert it to a wrapper class type.

static void create1() {
	//If it is a reference type array, the reference type List will be returned as expected....
	String[] words = {"abc","def","ghi"};
	List<String> list1 = Arrays.asList(words);
}

static void create2() {
	//AsList an array of primitive types()If it is used as an argument of, a list with 1 element is returned because "the array becomes one element in the list".
	// list2.size()Is 1.
	int[] numbers = {1,2,3,4,5,6,7,8,9,10};
	List<int[]> list2 = Arrays.asList(numbers);
	System.out.println("length of list2:" + list2.size());
}

static void create3() {
	//Variadic argument asList()If you pass it to, the list will be generated as expected even if the argument is an integer value (= int).
	// list3.size()Is 10.
	List<Integer> list3 = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
	System.out.println("length of list3:" + list3.size());
}

Summary

  1. The list obtained by Arrays.asList () is a fixed length list.
  2. If an array of primitive type is specified in the argument of Arrays.asList (), the elements of the array are not expanded and the array itself becomes one element of the list of return values.

Recommended Posts

[Java] Points to note with Arrays.asList ()
Java to play with Function
Connect to DB with Java
Connect to MySQL 8 with Java
Study Java with Progate Note 1
Java to learn with ramen [Part 1]
Dare to challenge Kaggle with Java (1)
I tried to interact with Java
My note: Introducing Java to Ubuntu
Java, arrays to start with beginners
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
[Note] How to get started with Rspec
Introduction to algorithms with java --Search (depth-first search)
Java Realm is difficult to handle 3 points
How to use Java Scanner class (Note)
Easy to trip with Java regular expressions
Introduction to algorithms with java --Search (breadth-first search)
[Java] Introduction to Java
Introduction to java
Java8 / 9 Beginners: Stream API addiction points and how to deal with them
Challenge to deal with garbled characters with Java AudioSystem.getMixerInfo ()
[Java] How to test for null with JUnit
I tried to make Basic authentication with Java
Introduction to algorithms with java --Search (bit full search)
Deploy Java web app to Azure with maven
Try to link Ruby and Java with Dapr
How to use Java framework with AWS Lambda! ??
I want to use java8 forEach with index
How to use Segmented Control and points to note
How to use Java API with lambda expression
Getting started with Kotlin to send to Java developers
Try to implement TCP / IP + NIO with JAVA
[Java] Article to add validation with Spring Boot 2.3.1.
Easy to make LINE BOT with Java Servlet
I tried to break a block with java (1)
[Beginner] Points to be aware of after Java exercises / Inheritance / Abstract method [Note 26]
Install java with Homebrew
Java abstract modifier [Note]
How to call functions in bulk with Java reflection
List processing to understand with pictures --java8 stream / javaslang-
Submit a job to AWS Batch with Java (Eclipse)
Changes from Java 8 to Java 11
Sum from Java_1 to 100
[Note] Apply password protection to Excel sheets with NPOI
Install Java with Ansible
[Note] Methods ending with?
[Java 11] I tried to execute Java without compiling with javac
[Java] How to omit spring constructor injection with Lombok
How to deploy Java to AWS Lambda with Serverless Framework
[Java Silver] Summary of points related to lambda expressions
java: How to write a generic type list [Note]
[Java] Connect to MySQL
# 2 [Note] I tried to calculate multiplication tables in Java.
[Java] How to encrypt with AES encryption with standard library
Comfortable download with JAVA
Java JUnit brief note
[java] Java SE 8 Silver Note
[Java] Refer to and set private variables with reflection
Switch java with direnv
Kotlin's improvements to Java