CS61b class 3

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.
reference type的equal

3.4 passing parameters

给函数传参数的时候,和equal的规则是一致的,也是copy the bits, pass by value
这道题选B。instance的减少的理解非常直观,int不会改变是因为存储的本来就是9这个数字而不是数字的地址,doStuff这个方法copy了x,也在方法copy的数字中改变了该数字,但是原有的x不会改变。
3.5 GRoE
visualization of code

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 可以调用本对象的所有方法和属性。自己理解了一下,感觉在这个方法里面,像是指向当前对象的指针。别的区分同名变量和引用构造函数的用法在碰到了之后再深入学习。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值