java

How to convert Array to List in Java

Often it is necessary to convert an array into a list. The easiest way to convert an array into a list is the method asList() of the Java Util class java.util.Arrays.

String[] str = new String[]{"Alex", "Jean", "Emily", "Bob"};
        
List<String> list = Arrays.asList(str);

 
The problem is that Arrays.asList() returns an immutable List, an instance of a list that cannot be changed. If an attempt is now made to change the list as in the following code, an UnsupportedOperationException is thrown, since the method is of course not supported in an immutable list (because an add() changes the list).

list = Arrays.asList(str);

list.add("Yohan"); // throws UnsupportedOperationException

In cases where the list still needs to be changed, or a certain list implementation such as ArrayList or LinkedList is required, the immutable list can be passed directly to the constructor:

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

list.add("Yohan");
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

Leave a Reply

Your email address will not be published. Required fields are marked *