This works, as long as the String
ends in a comma, like your example.
String numbersArray = "1, 2, 3, 14, 5,";
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, j, n = numbersArray.length(); i < n; i = j + 1) {
j = numbersArray.indexOf(",", i);
list.add(Integer.parseInt(numbersArray.substring(i, j).trim()));
}
However, it's pretty useless, as on my machine it's about 2 times slower than the original.
This next solution, on the other hand, is surprisingly fast. I tested it on lists of 50000 integers obtained using Math.abs(random.nextInt())
and it was about 4 times faster than the original.
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, a = 0, n = numbersArray.length(); i < n; i++) {
char c = numbersArray.charAt(i);
if (c == ',') {
list.add(a);
a = 0;
} else if (c != ' ') {
a = a * 10 + (c - '0');
}
}
And this is about twice as fast again:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0, a = 0, n = numbersArray.length(); i < n; i++) {
switch(numbersArray.charAt(i)) {
case ',': list.add(a); a = 0; break;
case ' ': break;
case '0': a = a * 10; break;
case '1': a = a * 10 + 1; break;
case '2': a = a * 10 + 2; break;
case '3': a = a * 10 + 3; break;
case '4': a = a * 10 + 4; break;
case '5': a = a * 10 + 5; break;
case '6': a = a * 10 + 6; break;
case '7': a = a * 10 + 7; break;
case '8': a = a * 10 + 8; break;
case '9': a = a * 10 + 9; break;
default: throw new AssertionError();
}
}