Java 如何将字符串拆分为 ArrayList?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23172397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a String to an ArrayList?
提问by
I know there is a String split method that returns an array but I need an ArrayList.
我知道有一个 String split 方法可以返回一个数组,但我需要一个 ArrayList。
I am getting input from a textfield (a list of numbers; e.g. 2,6,9,5
) and then splitting it at each comma:
我从文本字段(数字列表;例如2,6,9,5
)获取输入,然后在每个逗号处将其拆分:
String str = numbersTextField.getText();
String[] strParts = str.split(",");
Is there a way to do this with an ArrayList instead of an array?
有没有办法用 ArrayList 而不是数组来做到这一点?
采纳答案by Boann
You can create an ArrayList from the array via Arrays.asList:
您可以通过Arrays.asList从数组创建一个 ArrayList :
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(textField.getText().split(",")));
If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):
如果你不需要它专门是一个 ArrayList,并且可以使用任何类型的 List,你可以直接使用 Arrays.asList 的结果(这将是一个固定大小的列表):
List<String> parts = Arrays.asList(textField.getText().split(","));
回答by ced-b
There is no such thing as a Split functionfor list, but you can do the split and then convert to a List
没有列表的拆分函数之类的东西,但是您可以进行拆分然后转换为列表
List myList = Arrays.asList(myString.split(","));