【问题标题】:Load List in Java from its String representation?从其字符串表示中加载Java中的列表?
【发布时间】:2011-07-11 14:24:14
【问题描述】:

我知道这可以通过编写函数轻松完成,但是,我想知道是否有一种快速便捷的方法可以从 String 表示中加载 Java 中的 List。

我举个小例子:

List<String> atts = new LinkedList<String>();
atts.add("one"); atts.add("two"); atts.add("three”);
String inString = atts.toString()); //E.g. store string representation to DB
...
//Then we can re-create the list from its string representation?
LinkedLisst<String> atts2 = new LinkedList<String>();

谢谢!

【问题讨论】:

标签: java linked-list


【解决方案1】:

您不想为此使用 toString()。相反,您想使用 java 的序列化方法。这是一个例子:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(stream);
out.writeObject(list);
stream.close();
// save stream.toByteArray() to db

// read byte
ByteArrayInputStream bytes = ...
ObjectInputStream in = new ObjectInputStream(bytes);
List<String> list = in.readObject();

这是一个更好的解决方案,因为您不必拆分或解析任何内容。您还可以使用其他序列化方法,例如 json 或 xml。我上面展示的内容是用 Java 构建的。

【讨论】:

  • 谢谢,但请您简单解释一下上面的代码。例如,代码的第 2 行和第 4 行中使用的“流”变量来自哪里?
  • Larry,流 var 来自第 1 行。第 1 部分用于写入,第 2 部分用于读取。更多信息请看这里java.sun.com/developer/technicalArticles/Programming/…
  • 问题是当我调用stream.getBytes()时,它返回一个错误说该方法没有为这个类型定义?!
  • 对不起,它实际上是调用toByteArray()。这是java文档download.oracle.com/javase/6/docs/api/java/io/…
【解决方案2】:

//那么我们可以从它的字符串表示中重新创建列表吗?

一种选择是同意使用已知格式来转换字符串表示和从字符串表示转换。我会在这里使用 CSV,因为这更简单,除非您的原始字符串本身中有逗号。

String csvString = "one,two,three";
List<String> listOfStrings = Arrays.asList(csvString.split(","));

【讨论】:

    【解决方案3】:

    没有可靠的方法来做到这一点。 Lists 的 toString() 方法并非旨在输出可以可靠地用作序列化列表的方法。

    这是行不通的。看看你的例子的这个小改动:

    public static void main(String[] args) {
        List<String> atts = new LinkedList<String>();
        atts.add("one");
        atts.add("two");
        atts.add("three, four");
        String inString = atts.toString();
        System.out.println("inString = " + inString);
    }
    

    这个输出

    inString = [one, two, three, four]
    

    这看起来像列表包含四个元素。但我们只添加了三个。没有可行的方法来确定原始来源列表。

    【讨论】:

    • 是的,这是真的。这就是为什么我认为序列化是最好的选择。
    【解决方案4】:

    您可以从其字符串表示中创建一个列表。如果字符串包含“、”或字符串为null,则它可能不是完全相同的列表,但您可以这样做,它适用于许多用例。

    List<String> strings = Arrays.asList("one", "two", "three");
    String text = strins.asList();
    // in this case, you will get the same list.
    List<String> strings2=Arrays.asList(text.substring(1,text.length()-1).split(", "));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2015-10-03
      • 2016-12-01
      • 2020-01-08
      • 1970-01-01
      • 2022-12-22
      相关资源
      最近更新 更多