一次调用将 ArrayList.toString() 转换回 ArrayList [英] convert ArrayList.toString() back to ArrayList in one call
问题描述
我有一个 ArrayList
的 toString()
表示.
将 toString()
值复制到剪贴板,我想将它复制回我的 IDE 编辑器,并在一行中创建 ArrayList
实例.事实上,我真正在做的是:
- 我的 ArrayList.toString() 包含设置单元测试所需的数据.
- 我想将此 ArrayList.toString() 复制到我的编辑器中以针对此边缘情况构建测试
- 我不想手动解析任何东西
我的输入是这样的:
[15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.02.1, 17.09, 16.32, 17.05, 17.05, 17.05, 17.05, 18.16,以下不起作用:
Arrays.asList()
- 谷歌集合
Lists.newArrayList()
建议?
Substring 花括号,在 、
(逗号和空格)上拆分,最后将它提供给 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, 17.8.2, 17.82列表<字符串>list = Arrays.asList(s.substring(1, s.length() - 1).split(", "));
请注意,这适用于您的特定情况,但并非适用于所有情况.例如,您可能有一个字符串列表,其中至少有一个包含后续逗号和空格.拆分将失败.
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?
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.
这篇关于一次调用将 ArrayList.toString() 转换回 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!