Created
July 27, 2010 21:29
-
-
Save rpdillon/492902 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class StringListSerialize { | |
public static final String DELIMITER = ","; | |
public static String serialize(List<String> strings) { | |
StringBuilder metadata = new StringBuilder(); | |
StringBuilder concat = new StringBuilder(); | |
for (String s: strings) { | |
metadata.append(s.length()); | |
metadata.append(DELIMITER); | |
concat.append(s); | |
} | |
return metadata.length() + DELIMITER + metadata.toString() + concat.toString(); | |
} | |
public static List<String> deserialize(String serializedList) { | |
// The List we'll return | |
List<String> result = new ArrayList<String>(); | |
int lengthIndex = serializedList.indexOf(DELIMITER); | |
int metadataLength = Integer.parseInt(serializedList.substring(0, lengthIndex)); | |
// The index at which to start reading data | |
int currentIndex = lengthIndex + 1 + metadataLength; | |
String[] metadata = serializedList.substring(lengthIndex + 1, lengthIndex + 1 + metadataLength).split(DELIMITER); | |
for(String strLength: metadata) { | |
int length = Integer.parseInt(strLength); | |
result.add(serializedList.substring(currentIndex, currentIndex+length)); | |
currentIndex = currentIndex + length; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
List<String> strings = new ArrayList<String>(); | |
strings.add("This"); | |
strings.add("Is"); | |
strings.add("A"); | |
strings.add("Test"); | |
strings.add("Collection"); | |
String ser = serialize(strings); | |
System.out.println(ser); | |
for (String s : deserialize(ser)) { | |
System.out.println(s); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment