Java ArrayList 的 (ArrayList).toString 的逆运算是什么?
我正在使用 ArrayList 的 toString 方法将 ArrayList 数据存储到字符串中。我的问题是,我该如何走另一条路?是否有现有方法可以将 String 实例中的数据解析回 ArrayList ?
I am using the toString
method of ArrayList
to store ArrayList
data into a String. My question is, how do I go the other way? Is there an existing method that will parse the data in the String
instance back into an ArrayList
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
简短的回答是“否”。没有简单的方法可以从字符串重新导入对象,因为某些类型信息在
toString()
序列化中丢失。但是,对于特定格式和特定(已知)类型,您应该能够编写代码来手动解析字符串:
从序列化形式重新构造对象通常称为反序列化
The short answer is "No". There is no simple way to re-import an Object from a String, since certain type information is lost in the
toString()
serialization.However, for specific formats, and specific (known) types, you should be able to write code to parse a String manually:
Reconstituting objects from their serialized form is generally called deserialization
这是一个类似的问题:
Reverse(解析输出) of Arrays.toString(int[ ])
这取决于您在 ArrayList 中存储的内容,以及这些对象是否可以轻松地从其字符串表示形式重建。
Here's a similar question:
Reverse (parse the output) of Arrays.toString(int[])
It depends on what you're storing in the ArrayList, and whether or not those objects are easily reconstructed from their String representations.
我建议使用一些标准格式和库来代替。
JSON 可能是语法上最接近的。
或者,某些基于 XML 或序列化的解决方案也可以工作。当然,这一切都取决于您的需求。
I would recommend using some standard format with a library for it instead.
JSON is probably the closest syntactically.
Alternatively some XML or serialization based solution could work too. It all depends on your needs of course.
ArrayList由什么组成?正如其他人所说,在某些情况下这可能是不可能的,但很有可能并且保证可以工作如果:
可以明确地识别数组元素的每个字符串表示形式(例如可以是如果 ArrayList 由
Integer
组成)则
有一种方法可以从 String 表示形式创建原始类型的对象。我发现使用静态方法
fromString
来做到这一点是最优雅的,
当然,这模仿了整个(反)序列化框架。
What does the ArrayList consist of? As others said, it may be impossible in certain cases, but quite possible and guaranteed to work if:
each string representation of element of the array can be identified unambiguously (as it can be for example if the ArrayList consists of
Integer
s)there is a way to create an object of original type from its String representation. I find it most elegant to do this using a static method
fromString
Of course, this mimics the whole (de)serialization framework.
阿帕奇共享ftw。
Apache Commons ftw.
如果上面给出编译错误。 (不能在 StringTokenizer 上使用 forEach)
In case the above gives a compilation error. (Can't use forEach on StringTokenizer)