无法序列化/反序列化ArrayList 是一个常见的问题,通常出现在尝试将 ArrayList 对象转换为字符串或其他格式以便存储或传输时。这是因为 ArrayList 类并不实现 Serializable 接口,也没有提供默认的序列化/反序列化方法。
以下是一些解决方案:
import java.io.*;
public class ArrayListSerialization {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
try {
FileOutputStream fileOut = new FileOutputStream("arrayList.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(arrayList);
out.close();
fileOut.close();
FileInputStream fileIn = new FileInputStream("arrayList.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<String> deserializedList = (ArrayList<String>) in.readObject();
in.close();
fileIn.close();
System.out.println(deserializedList);
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("ArrayList class not found");
c.printStackTrace();
}
}
}
import com.google.gson.Gson;
public class ArrayListSerialization {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
Gson gson = new Gson();
String json = gson.toJson(arrayList);
System.out.println(json);
ArrayList<String> deserializedList = gson.fromJson(json, ArrayList.class);
System.out.println(deserializedList);
}
}
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class ArrayListSerialization {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
String serializedList = arrayList.stream().collect(Collectors.joining(","));
System.out.println(serializedList);
ArrayList<String> deserializedList = new ArrayList<>(Arrays.asList(serializedList.split(",")));
System.out.println(deserializedList);
}
}
总之,无法序列化/反序列化 ArrayList 的问题可以通过使用 Java 自带的序列化方法、第三方库或者 Stream API 进行解决。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云