开发者

Load List in Java from its String representation?

I know this can easily be done by writing a function, however, I was wondering if there was a quick and convenient way to load a List in Java开发者_如何学Go from its String representation.

I will give a small example:

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

Thnx!


You wouldn't want to use toString() for this. Instead you want to use java's serialize methods. Here is an example:

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

This is a better solution because you don't have to split or parse anything. You can also use other methods of serilaizing such as json or xml. What I have showed above is built in Java.


//Then we can re-create the list from its string representation?

One option would be to agree to use a known format for both converting to and from the string representation. I would go with CSV here for that's simpler unless you have commas in your original string itself.

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


There is not a reliable way to do this. The toString() method for Lists is not designed to output something that can be reliably used as a way to serialise the list.

Here's way it can't work. look at this small change to your example:

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

This outputs

inString = [one, two, three, four]

This looks like the list contains four elements. But we only added three. There is not feasible way to determine the original source list.


You can create a List from its String representation. It may not be exactly the same List if the Strings contain a ", ", or a String is null but you can do it and it will work for many usecases.

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(", "));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜