发布新日志

  • Java premitive data and Object 赋值

    2012-10-02 23:02:59

    最近开始学习Java,在看Think in Java,看了没几页就发现自己之前在用Groovy写脚本时出现的一些问题在书中找到了理论解释 哈哈,很喜欢这本书,准备坚持看下去,然后结合自己在工作中的一些问题 在此记录一下,加深理解,不时的来看看

    今天看到Primitive Data Type 和 Object得赋值:

    之前在写脚本时曾经如下写:

    List l1 = new ArrayList()
    List l2 = new ArrayList()

    l1.add(1)
    l2.add(l1);

    l1.clear();
    print l2;

    本来是想输出l2作为一个多维List,结果每次运行l2都是空的,不明白是怎么回事。请教别人,知道是因为l1.clear()一句把l1清空了,但同时也清空了l2;

    Think in Java 中指出了原因:

    Java中有primitive data type的赋值,也有ojbect的赋值,两者是不一样的;

    Primitive data type: 例如
    b = 3;
    a = b; // b's contents are copied to a
    a = 4; // a is assigned with value 4
    print b; // b is still 3, not affected.

    Object:
    Class1 c1 = new Class1();// c1 is just a reference
    Class1 c2 = new Class1(); // same to c2
    c1=c2; // both c1 and c2 contain the same reference, thus pointing to the same object
    if you change C2 or C1's values, the other one will be changed accordingly
Open Toolbar