Reputation: 333
What I got it's this instruction that gives me back a String[]
object:
string.trim().split(" ");
The content using Arrays.asList(string.trim().split(" "))
it's something like:
[4, 3, 2, 5, -10, 23, 30, 40, -3, 30]
So its content is made up by numbers. What I want it's to convert the String[]
object to an int[]
one. How can I do that without parsing every single string to a int?
Upvotes: 0
Views: 70
Reputation: 65851
You can kind of do it without loops but you only get a List<Integer>
not an int[]
.
private static class IntegerAdapter extends AbstractList<Integer> implements List<Integer> {
private final List<String> theList;
public IntegerAdapter(List<String> strings) {
this.theList = strings;
}
public IntegerAdapter(String[] strings) {
this(Arrays.asList(strings));
}
@Override
public Integer get(int index) {
return Integer.parseInt(theList.get(index));
}
@Override
public int size() {
return theList.size();
}
}
public void test(String[] args) {
String test = "4 3 2 5 -10 23 30 40 -3 30";
String[] split = test.split(" ");
IntegerAdapter adapter = new IntegerAdapter(split);
// Look ma! No loops :)
System.out.println(adapter.get(4));
}
Upvotes: 1