How to convert comma separated string to ArrayList in Java
•
Java
See the English answer > how to convert comma separated string to ArrayList? 23
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); } } }
It gives me a runtime error as shown in the figure
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)
Because I tried to force list to ArrayList
Solution
Arrays. The ArrayList returned by aslist is not Java util. ArrayList. It is Java util. Arrays. ArrayList. So you can't cast it to Java util. ArrayList.
You need to pass the list to Java util. Constructor for ArrayList class:
List<String> items = new ArrayList<String>(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));
Alternatively, you can simply assign results:
List<String> items = Arrays.asList(CommaSeparated.split("\\s*,\\s*"));
Note, however, that arrays Aslist returns a fixed - size list You cannot add or remove anything from it If you want to add or delete something, you should use the first version
P. S: you should use list as the reference type instead of ArrayList
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码