Search code examples
javacollections

Java convert String[] to int[]


I have a String[], where each element is convertible to an integer. What's the best way I can convert this to an int[]?

int[] StringArrayToIntArray(String[] s)
{
    ... ? ...
}

Solution

  • public static int[] StringArrToIntArr(String[] s) {
       int[] result = new int[s.length];
       for (int i = 0; i < s.length; i++) {
          result[i] = Integer.parseInt(s[i]);
       }
       return result;
    }
    

    Simply iterate through the string array and convert each element.

    Note: If any of your elements fail to parse to an int this method will throw an exception. To keep that from happening each call to Integer.parseInt() should be placed in a try/catch block.