Java premitive data and Object 赋值

上一篇 / 下一篇  2012-10-02 23:02:59 / 个人分类:Java

最近开始学习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

TAG: java Object object Java Primitives Assignment 赋值

 

评分:0

我来说两句

日历

« 2024-03-17  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 10371
  • 日志数: 15
  • 书签数: 1
  • 建立时间: 2008-12-01
  • 更新时间: 2014-09-02

RSS订阅

Open Toolbar