2009-07-15

Java : 参照渡しのメモ


Class1.java
import java.util.ArrayList;
import java.util.List;

public class Class1 {

    public static void main(String[] args) {
      Class1.sample1();
      Class1.sample2();
      Class1.sample3();
    }

    private static void sample1() {
      System.out.println("sample 1 ");

      List<Info> listA = new ArrayList<Info>();
      for (int i=0; i<4; i++) {
        Info info = new Info();
        info.init("id_" + Integer.toString(i), "name_" + Integer.toString(i));
        listA.add(info);
      }
      List<Info> listB = new ArrayList<Info>(listA);
        
      print(listA, listB);
    }

    private static void sample2() {
        System.out.println("sample 2 ");

        List<Info> listA = new ArrayList<Info>();
        for (int i=0; i<4; i++) {
            Info info = new Info();
            info.init("id_" + Integer.toString(i), "name_" + Integer.toString(i));
            listA.add(info);
        }
        List<Info> listB = (ArrayList<Info>) ((ArrayList<Info>) listA).clone();

      print(listA, listB);
    }

    private static void sample3() {
      System.out.println("sample 3 ");

        List<Info> listA = new ArrayList<Info>() {
            @Override
            public Object clone() {
                List<Info> list = new ArrayList<Info>();
                for (Info info : this) {
                    list.add(info.clone());
                }
                return list;
            }
        };
      for (int i=0; i<4; i++) {
        Info info = new Info();
        info.init("id_" + Integer.toString(i), "name_" + Integer.toString(i));
        listA.add(info);
      }
      List<Info> listB = (ArrayList<Info>) ((ArrayList<Info>) listA).clone();

      print(listA, listB);
    }

    private static void print(List<Info> listA, List<Info> listB) {
      System.out.println("list A : " + listA.toString());
      System.out.println("list B : " + listB.toString());
    }
}


Info.java
public class Info implements Cloneable {

    private String id;
    private String name;

    public Info() {
    }

    public void init(String i, String n) {
        this.id = i;
        this.name = n;
    }

    public Info clone() {
        Info newInfo = new Info();
        newInfo.init(this.id, this.name);
        return newInfo;
    }
}


実行結果
sample 1 
list A : [Info@1bc4459, Info@12b6651, Info@4a5ab2, Info@1888759]
list B : [Info@1bc4459, Info@12b6651, Info@4a5ab2, Info@1888759]
sample 2 
list A : [Info@6e1408, Info@e53108, Info@f62373, Info@19189e1]
list B : [Info@6e1408, Info@e53108, Info@f62373, Info@19189e1]
sample 3 
list A : [Info@7c6768, Info@1690726, Info@5483cd, Info@9931f5]
list B : [Info@19ee1ac, Info@1f1fba0, Info@1befab0, Info@13c5982]




うへぇ。 sample3 は実用的ではないね。
しかし、 java.util.ArrayList#clone() では java.lang.CloneNotSupportedException は発生しないのか。



環境
java : jdk160_05(JDev11g 付属)
OS : Windows XP Pro sp2