練習問題3.10(未完)
う〜ん、わからん。。。
多分こうじゃないんだろうけど、とりあえず出来たところまで;;
1つのリストに対する変更は、他方のリストには影響しないが、リストが参照しているオブジェクトに対する変更は、他方のリストから見えます。
↑これをどうすれば良いか分からない。
下で言うと自分のメンバ変数Objへの変更は自分のみで、nextNodeのObjへの変更はもう一方から見えるって理解であってるのかな??
public class LinkedList implements Cloneable{ private Object Obj; private LinkedList nextNode; //コンストラクタ public LinkedList(Object Obj,LinkedList nextNode) { this.Obj = Obj; this.nextNode = nextNode; } //コンストラクタ public LinkedList(Object Obj) { this(Obj,null); } public void show(){ System.out.println(Obj.getClass()); if (Obj instanceof Vehicle) { Vehicle tmpVehicle = (Vehicle) Obj; tmpVehicle.print(); } if(nextNode!=null) nextNode.show(); } public String toString(){ if (Obj instanceof Vehicle) { String tmpv; Vehicle tmpVehicle = (Vehicle) Obj; tmpv = tmpVehicle.toString(); if(nextNode!=null) tmpv += nextNode.toString(); return tmpv; } return null; } public Object getObj(){ return Obj; } public void setObj(Object Obj){ this.Obj = Obj; } public LinkedList getNextNode(){return nextNode;} public void setNextNode(LinkedList nextNode){this.nextNode = nextNode;} public int countList(){ if(nextNode==null) return 1; else return 1 + nextNode.countList(); } public LinkedList clone(){ try{ LinkedList ls = (LinkedList)super.clone(); if(ls.nextNode!=null) ls.nextNode = nextNode.clone(); return ls; }catch(CloneNotSupportedException e){ throw new InternalError(e.toString()); } } public static void main(String args[]){ Vehicle car1 = new Vehicle("Taro"); Vehicle car2 = new Vehicle("Hanako"); LinkedList node2 = new LinkedList(car2); LinkedList node1 = new LinkedList(car1,node2); LinkedList cloneNode = node1.clone(); Vehicle tmpVehicle = (Vehicle)cloneNode.getNextNode().getObj(); tmpVehicle.setOwner("Ichiro"); Vehicle tmpMyVehicle = (Vehicle)cloneNode.getObj(); tmpMyVehicle.setOwner("Yukio"); System.out.println(node1); System.out.println("----"); System.out.println(cloneNode); } }