Search code examples
javaarraylistsplit

How to split a String to an ArrayList?


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?


Solution

  • 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(","));