---
title: "ArrayList的elementData声明为transient，为什么还可以序列化?<转>"
author: "lixusign"
date: "2011-05-28T23:20:14Z"
tags: ["Java", "虚拟机"]
categories: ["编程语言"]
slug: "arraylist-elementdata-transient"
draft: false
lastmod: "2011-05-28T23:22:48Z"
id: 1063324
url: "https://lixusign.iteye.com/blog/1063324"
---

\[code="java"] private transient E\[] elementData; private transient E\[] elementData; 声明为transient，为什么还可以序列化成功呢？ \[/code] 我的回答是ArrayList重写了 \[code="java"]private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ int expectedModCount = modCount; // Write out element count, and any hidden stuff s.defaultWriteObject(); // Write out array length s.writeInt(elementData.length); // Write out all elements in the proper order. for (int i=0; i extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /\** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. \*/ private E\[] elementData; 。。。。。。。。 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ int expectedModCount = modCount; // Write out element count, and any hidden stuff s.defaultWriteObject(); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /\** * Reconstitute the `ArrayList` instance from a stream (that is, * deserialize it). \*/ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in size, and any hidden stuff s.defaultReadObject(); } } \[/code] 把transient去掉，write/readObject采用默认方式。 测试下MyArraylist序列化功能： \[code="java"]MyArrayList al = new MyArrayList(); al.add("sssssssssssssssss"); al.add("bbbbbbbbbbbbbbbbbbt"); al.add("gggggggggggggggggg"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\\\al.tmp")); oos.writeObject(al); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\\\al.tmp")); MyArrayList a = (MyArrayList)ois.readObject(); for(String s: a) { System.out.println(s); } \[/code] 输出结果为： \[code="java"] sssssssssssssssss bbbbbbbbbbbbbbbbbbt gggggggggggggggggg \[/code] 到此证明：引用序列化无效的说法是错误的，这点在ObjectOutputStream中也有说明。 那是为什么呢？ 既然是数组，要序列化到文件中，那就单独测试下数组对象的序列化和反序列化吧 \[code="java"]String\[] stra = new String\[4]; stra\[0] = "mmmmmmmmmm"; stra\[2] = "nnnnnnnnnn"; oos = new ObjectOutputStream(new FileOutputStream("D:\\\\sa.tmp")); oos.writeObject(stra); ois = new ObjectInputStream(new FileInputStream("D:\\\\sa.tmp")); String\[] str = (String\[])ois.readObject(); for(String s: str) { System.out.println(s); } \[/code] 输出结果为： \[code="java"] mmmmmmmmmm null nnnnnnnnnn null \[/code] 从输出结果来看，数组序列化时，不管是否有值，都会将整个数组序列化到文件中。 由此可以看出，比较靠谱的原因是： ArrayList是会开辟多余空间来保存数据的，而系列化和反序列化这些没有存放数据的空间是要消耗更多资源的，所以ArrayList的数组就声明为transient，告诉虚拟机这个你别管，我自己来处理，然后就自己实现write/readObject方法，仅仅系列化已经存放的数据。