Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - convert ArrayList.toString() back to ArrayList in one call

I have a toString() representation of an ArrayList.

Copying the toString() value to clipboard, I want to copy it back into my IDE editor, and create the ArrayList instance in one line. In fact, what I'm really doing is this:

  • my ArrayList.toString() has data I need to setup a unit test.
  • I want to copy this ArrayList.toString() into my editor to build a test against this edge case
  • I don't want to parse anything by hand

My input looks like this:

[15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16]

The following do not work:

  • Arrays.asList()
  • google collections Lists.newArrayList()

Suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Substring the braces away, split it on , (comma and space) and finally feed it to Arrays#asList().

 String s = "[15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16]";
 List<String> list = Arrays.asList(s.substring(1, s.length() - 1).split(", "));

Note that this will work in your particular case, but not in all circumstances. You may for example have a list of strings of which at least one contains a subsequent comma and space. The split would then fail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...