Java 中传输数组的方法有:作为方法参数作为对象通过序列化通过 JSON
如何使用 Java 传输数组
Java 中,您可以通过以下方法传输数组:
1. 作为方法参数
示例:
public static void printArray(int[] array) { for (int i : array) { System.out.println(i); } }
2. 作为对象
Object 类可以容纳任何类型的对象,包括数组。示例:
public static void printArray(Object array) {
int[] intArray = (int[]) array; // 强制转换为 int[]
for (int i : intArray) {
System.out.println(i);
}
}3. 通过序列化
Serializable 接口。示例:
// 实现 Serializable 接口
class MyArray implements Serializable {
public int[] array;
}
// 序列化数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(myArray);
// 接收方反序列化数组
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
MyArray receivedArray = (MyArray) in.readObject();4. 通过 JSON
示例:
// 转换为 JSON 字符串 Gson gson = new Gson(); String jsonString = gson.toJson(myArray); // 接收方反序列化 JSON 字符串 MyArray receivedArray = gson.fromJson(jsonString, MyArray.class);