How to convert comma separated string to ArrayList in Java

I have a comma separated section that I need to convert to an ArrayList. I tried this way

import java.util.ArrayList; import java.util.Arrays; public class Test { public static void main(String[] args) { String CommaSeparated = "item1 , item2 , item3"; ArrayList<String> items = (ArrayList)Arrays.asList(CommaSeparated.split("\\s*,\\s*")); for(String str : items) { System.out.println(str); } } } 

This gives me a runtime error as shown

 Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList at com.tradeking.at.process.streamer.Test.main(Test.java:14) 

since I was trying to force the List to be an array of List.

+6
source share
5 answers

ArrayList returned by Arrays.asList , not java.util.ArrayList . This is java.util.Arrays.ArrayList . Therefore, you cannot direct it to java.util.ArrayList .

You need to pass the list to the constructor of the java.util.ArrayList class:

 List<String> items = new ArrayList<String>(Arrays.asList(CommaSeparated.split("\\s*,\\s*"))); 

or you can just assign the result:

 List<String> items = Arrays.asList(CommaSeparated.split("\\s*,\\s*")); 

but notice, Arrays.asList returns a list of fixed sizes. You cannot add or remove anything in it. If you want to add or remove something, you must use the 1st version.

PS: You should use List as a reference type instead of ArrayList .

+19
source

You can't just throw objects like sweets. Arrays.asList() does not return an ArrayList , so you cannot use it (it returns an unmodifiable list).

However, you can do new ArrayList(Arrays.asList(...));

+2
source

Do I need to be an ArrayList ? Usually you want to use the most general form. If you are using List , just try:

 List<String> items = Arrays.asList(...); 

You can still iterate over it just like you.

+1
source
 String CommaSeparated = "item1 , item2 , item3"; ArrayList<String> items = new ArrayList(Arrays.asList(CommaSeparated.split("\\s*,\\s*"))); for(String str : items) { System.out.println(str); } 
+1
source

Try using the following code.

String [] temp;

  /* delimiter */ String delimiter = ","; /* * given string will be split by the argument delimiter provided. */ temp = parameter.split(delimiter); ArrayList<String> list = new ArrayList<String>(); for (int l = 0; l < temp.length; l++) { list.add(temp[l]); } 
0
source

Source: https://habr.com/ru/post/951216/


All Articles