- 问题引入
上图中,赋给b海象的weight会改变a海象的weight,但x的赋值又不会改变y的赋值
Bits
要解释上图的问题,我们应该从Java的底层入手
相同的二进制编码,却因为数据类型不同,输出不同的值
变量的声明
基本类型
Java does not write anything into the reserved box when a variable is declared. In other words, there are no default values. As a result, the Java compiler prevents you from using a variable until after the box has been filled with bits using the = operator. For this reason, I have avoided showing any bits in the boxes in the figure above.
引用类型
When we declare a variable of any reference type (Walrus, Dog, Planet, array, etc.), Java allocates a box of 64 bits, no matter what type of object.
96位大于64位,这似乎有些矛盾:
在Java中:the 64 bit box contains not the data about the walrus, but instead the address of the Walrus in memory.
Gloden rule
练习
答案:B
解析:
- 在调用方法(函数)时,doStuff方法中的int x与main方法中的int x 实际上处于两个不同的scope(调用方法时会new 一个scope,并将main方法中的x变量的位都传递给doStuff方法中的x变量,即值传递),所以x = x - 5实际上只作用于doStuff方法中的x,而不是main方法中的x。
- 但对于引用类型来说,引用类型储存的是引用的地址,所以在进行值传递时传递的是对象的地址,所以doStuff方法中的int x与main方法中的walrus实际上指向相同的一个对象,这使得doStuff中执行的语句会作用于main方法中walrus指向的对象,所以反作用于main方法中的walrus
IntLists
使用递归求链表中元素的个数
/** Return the size of the list using... recursion! */
public int size() {if (rest == null) {return 1;}return 1 + this.rest.size();
}
Exercise: You might wonder why we don’t do something like if (this == null) return 0;. Why wouldn’t this work?
Answer: Think about what happens when you call size. You are calling it on an object, for example L.size(). If L were null, then you would get a NullPointer error!
不使用递归求元素个数
/** Return the size of the list using no recursion! */
public int iterativeSize() {IntList p = this;int totalSize = 0;while (p != null) {totalSize += 1;p = p.rest;}return totalSize;
}