原始較小我有它接受一個對象,並把它變成一個字節數組的函數:陣列的比原始對的ObjectOutputStream
public static byte[] serialize(Object obj) throws IOException {
try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
try(ObjectOutputStream o = new ObjectOutputStream(b)){
o.writeObject(obj);
}
return b.toByteArray();
}
}
當我使用上的原始類型此功能,輸出最終被大於相同基元的單一數組。
public static void main (String[] args) throws java.lang.Exception
{
System.out.format("byte single: %d, array: %d\n",
serialize((byte) 1).length, serialize(new byte[]{1}).length);
System.out.format("short single: %d, array: %d\n",
serialize((short) 1).length, serialize(new short[]{1}).length);
System.out.format("int single: %d, array: %d\n",
serialize((int) 1).length, serialize(new int[]{1}).length);
System.out.format("float single: %d, array: %d\n",
serialize((float) 1).length, serialize(new float[]{1}).length);
System.out.format("double single: %d, array: %d\n",
serialize((double) 1).length, serialize(new double[]{1}).length);
}
這將產生:
byte single: 75, array: 28 short single: 77, array: 29 int single: 81, array: 31 float single: 79, array: 31 double single: 84, array: 35
這到底是怎麼回事?爲什麼數組更小?這是一個Ideone for the issue