简体   繁体   中英

How to convert String[] that contains numbers to int[] in Java?

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?

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM