3.2 Primitive Types
Java中有八个primitive types:byte, short, int, long, float, double, boolean, char.
The golden rule of equals(GRoE)
- y = x copies all the bits from x into y
int x = 5;
y = x;
x = 2;
System.out.println("x is :"+x);
System.out.println("y is :"+y);
输出 x = 2 y = 5。
除了这八种primitive type之外,其余的所有类型都是reference type(reference to object),包括array。
前一节中关于walrus的类,某个instance等于另一个instance时,改动等于的那个instance,另一个也会改变。instance的赋值用box-and-pointer notation.
3.4 passing parameters
给函数传参数的时候,和equal的规则是一致的,也是copy the bits, pass by value
这道题选B。instance的减少的理解非常直观,int不会改变是因为存储的本来就是9这个数字而不是数字的地址,doStuff这个方法copy了x,也在方法copy的数字中改变了该数字,但是原有的x不会改变。
3.9 IntLists
这部分讲了list的数据结构,声明和定义一个IntList类,并添加用递归法和非递归法的计算list大小的method。
package hello_pkg;
public class IntList {
public int first;
public IntList rest;
public IntList(int f, IntList r){
first = f;
rest = r;
}
/** return the size of the list using recursion*/
public int size(){
if (rest == null){
return 1;
}
return 1 + this.rest.size();
}
/**return the size of the list using iteration*/
public int iterativeSize(){
IntList p = this;
int totalsize = 0;
while (p != null){
totalsize += 1;
p = p.rest;
}
return totalsize;
}
public static void main(String[] args){
IntList L = new IntList(15,null);
L = new IntList(10, L);
L = new IntList(14, L);
System.out.println(L.size());
System.out.println(L.iterativeSize());
}
}
需要注意的是JAVA中的this关键字,在当前语境下指的是当前对象的引用。this 关键字用来表示当前对象本身,或当前类的一个实例,通过 this 可以调用本对象的所有方法和属性。自己理解了一下,感觉在这个方法里面,像是指向当前对象的指针。别的区分同名变量和引用构造函数的用法在碰到了之后再深入学习。