java 反转(解析输出)的 Arrays.toString(int[])

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/456367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:27:38  来源:igfitidea点击:

Reverse (parse the output) of Arrays.toString(int[])

javaserializationtostring

提问by Thilo

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?

JDK 或 Jakarta Commons(或其他任何地方)中是否有一种方法可以解析 Arrays.toString 的输出,至少对于整数数组?

int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} );

回答by Sam

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

回答by Anderson

A sample with fastjson, a JSON library:

一个带有 fastjson 的示例,一个 JSON 库:

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

回答by André

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

您还可以使用 Apache Commons 的StringUtils 中的split/join