18

Is there in the JDK or Jakarta Commons (or anywhere else) a method that can parse the output of Arrays.toString, at least for integer arrays?

int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} );
Thilo
  • 257,207
  • 101
  • 511
  • 656

3 Answers3

26

Pretty easy to just do it yourself:

public class Test {
  public static void main(String args[]){
    int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} ));
  }

  private static int[] fromString(String string) {
    String[] strings = string.replace("[", "").replace("]", "").split(", ");
    int result[] = new int[strings.length];
    for (int i = 0; i < result.length; i++) {
      result[i] = Integer.parseInt(strings[i]);
    }
    return result;
  }
}
unholysampler
  • 17,141
  • 7
  • 47
  • 64
Sam
  • 6,240
  • 4
  • 42
  • 53
2

A sample with fastjson, a JSON library:

    String s = Arrays.toString(new int[] { 1, 2, 3 });
    Integer[] result = ((JSONArray) JSONArray.parse(s)).toArray(new Integer[] {});

Another sample with guava:

    String s = Arrays.toString(new int[] { 1, 2, 3 });
    Iterable<String> i = Splitter.on(",")
        .trimResults(CharMatcher.WHITESPACE.or(CharMatcher.anyOf("[]"))).split(s);
    Integer[] result = FluentIterable.from(i).transform(Ints.stringConverter())
        .toArray(Integer.class);
Anderson
  • 2,496
  • 1
  • 27
  • 41
-1

You can also use split/join from Apache Commons' StringUtils

André
  • 12,497
  • 6
  • 42
  • 44