List(CS61B学习记录)

  • 问题引入
    在这里插入图片描述

上图中,赋给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;
}

求第n个元素

在这里插入图片描述

相关推荐

  1. leetcode61-Rotate List

    2024-03-10 19:16:03       9 阅读
  2. 学习记录691@spring面试之bean的作用域

    2024-03-10 19:16:03       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-10 19:16:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-10 19:16:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-10 19:16:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-10 19:16:03       20 阅读

热门阅读

  1. react父组件调用子组件的方法

    2024-03-10 19:16:03       21 阅读
  2. spring boot对外部文件的访问

    2024-03-10 19:16:03       18 阅读
  3. 数据分析之Excel的使用

    2024-03-10 19:16:03       25 阅读
  4. python的http服务的使用

    2024-03-10 19:16:03       19 阅读
  5. RPC--一起学习吧之架构

    2024-03-10 19:16:03       24 阅读
  6. python3.9 处理excel来实现类似excel中的vlookup功能

    2024-03-10 19:16:03       21 阅读
  7. 卷积神经网络 (CNN)

    2024-03-10 19:16:03       22 阅读
  8. 【数据库】索引 视图 触发器 分页查询

    2024-03-10 19:16:03       18 阅读
  9. vue中表单数据规则验证

    2024-03-10 19:16:03       19 阅读