字节数组输入输出流
ByteArrayInputStream
给定该输出流一个字节数组,该输入流就会从数组中读取所有字节
ByteArrayOutputStream
该输出流内部维护着一个字节数组,使该输出流写出的字节,都保存了自身维护的数组上了
高效的深度复制
使用ByteArrayOutputStream和ByteArrayInputStream
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class CloneArrayList2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ArrayList<Person> person=new ArrayList<Person>();
person.add(new Person("张三",11));
person.add(new Person("李四",22));
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(person);
byte[] data=bos.toByteArray();
ByteInputStream bis=new ByteInputStream(bos.toByteArray(),data.length);
ObjectInputStream ois=new ObjectInputStream(bis);
ArrayList<Person> clone=(ArrayList<Person>)ois.readObject();
ois.close();
oos.close();
System.out.println(person==clone);//false
System.out.println(person.get(0)==clone.get(0));//false
System.out.println(person.equals(clone));//true
}
}