情感美文

Deep Copy And Shallow Copy

作者:本站 | 分类:情感控制| 浏览:144

	Deep Copy And Shallow Copy

,,,theMainObject1havefields"field1"ofinttype,and"ContainObject1",MainObject2iscreatedwith"field3"containingthecopiedvalueof"field1",thevaluesofitarecopiedtofield3butContainedObject1isanobject,,letsseewhatsdeepcopyWhatisDeepCopyAdeepcopycopiesallfields,,theMainObject1havefields"field1"ofinttype,and"ContainObject1",MainObject2iscreatedwith"field3"containingthecopiedvalueof"field1"and"ContainObject2",herewearewithwhementationSubject{Stringname;StringgetName(){name;}setName(Strings){name=s;}Subject(Strings){name=s;}}StudentCloneable{Subjectsubj;Stringname;SubjectgetSubj(){subj;}StringgetName(){name;}setName(Strings){name=s;}Person(Strings,Stringsub){name=s;subj=Subject(sub);}Objectclone(){{.clone();}(CloneNotSupportedExceptione){}}}CopyTest{main(String[]args){Studentstud=Student("John","Algebra");("OriginalObject:"+()+"-"+().getName());StudentclonedStud=(Student)();("ClonedObject:"+()+"-"+().getName());("Dan");().setSubjectName("Physics");("OriginalObjectafteritisupdated:"+()+"-"+().getName());("ClonedObjectafterupdatingoriginalobject:"+()+"-"+().getName());}}Outputis:OriginalObject:John-AlgebraClonedObject:John-AlgebraOriginalObjectafteritisupdated:Dan-PhysicsClonedObjectafterupdatingoriginalobject:John-PhysicsInthisexample,allIdidis,implementtheclassthatyouwanttocopywithClonableinterfaceandoverrideclone()(),thechangesmadeto"name"fieldoforiginalobject(Studentclass)isnotreflectedinclonedobjectbutthechangesmadeto"name"fieldofcontainedobject(Subjectclass){Subjectsubj;Stringname;SubjectgetSubj(){subj;}StringgetName(){name;}setName(Strings){name=s;}Person(Strings,Stringsub){name=s;subj=Subject(sub);}Objectclone(){{Students=Student(name,());s;}(CloneNotSupportedExceptione){}}}Outputis:OriginalObject:John-AlgebraClonedObject:John-AlgebraOriginalObjectafteritisupdated:Dan-PhysicsClonedObjectafterupdatingoriginalobject:Dan-PhysicsWell,ifyouobservehereinthe"Student"class,youwillseeonlythechangeinthe"clone()",,thenyouneedtoimplementCloneableinte,stantstoreandreaditbackwhenneeded,,whenyoudeepcopythroughserialization,youshouldmakesurethatallclassesintheobject{x;y;ColoredCircle(x,y){.x=x;.y=y;}getX(){x;}setX(x){.x=x;}getY(){y;}setX(x){.x=x;}}DeepCopy{main(String[]args){ObjectOutputStreamoos=ObjectInputStreamois={ColoredCirclec1=ColoredCircle(100,100);("Original="+c1);ColoredCirclec2=ByteArrayOutputStreambos=ByteArrayOutputStream();oos=ObjectOutputStream(bos);(c1);();ByteArrayInputStreambin=ByteArrayInputStream(());ois=ObjectInputStream(bin);c2=();("Copied="+c2);(200);(200);("Original="+c1);("Copied="+c2);}(Exceptione){("Exceptioninmain="+e);}{();();}}}Theoutputis:Original=x=100,y=100Copied=x=100,y=100Original=x=200,y=200Copied=x=100,y=100Allyouneedtodohereis:。

上一篇: Adobe Photoshop Source Code    下一篇:没有了
最近更新
精彩推荐
友情链接