2

I know there is a String split method that returns an array but I need an 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:

String str = numbersTextField.getText();
String[] strParts = str.split(",");

Is there a way to do this with an ArrayList instead of an array?

Boann
  • 48,794
  • 16
  • 117
  • 146

3 Answers3

7

You can create an ArrayList from the array via Arrays.asList:

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):

List<String> parts = Arrays.asList(textField.getText().split(","));
Boann
  • 48,794
  • 16
  • 117
  • 146
  • Thank you! I didn't understand this at first but when I put it in my code I get it now. I don't think I understand my own question after you edited it though.. lol Oh well, that don't matter :D –  Apr 19 '14 at 20:20
  • I hope I didn't change the meaning. What are you unsure of? – Boann Apr 19 '14 at 22:02
  • I didn't know the split method returned an array... I wasn't sure of the first sentence but I think I get it now :) –  Apr 21 '14 at 18:38
0

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(","));
ced-b
  • 3,957
  • 1
  • 27
  • 39
0

We can split like below.

List<String> valueSplitList = Arrays.asList(myString.split(","));
Satya Pendem
  • 307
  • 5
  • 13