Pergunta

Esta questão já tem uma resposta aqui:

Existe no JDK ou Jakarta Commons (ou em qualquer outro lugar) um método que pode analisar a saída de Arrays.toString, pelo menos para arrays de inteiros?

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

Solução

Muito fácil de fazê-lo apenas se:

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

Outras dicas

Uma amostra com fastjson, uma biblioteca JSON:

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

Outra amostra com goiaba:

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

Você também pode usar divisão / associar-se a partir do Apache Commons' StringUtils

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top