3.1Data Type and Type Checking (补充)

本文深入探讨了Java中的关键概念,包括基本数据类型及其包装类、不可变性和可变性、集合框架的使用以及空引用的处理。通过具体的例子说明了基本数据类型与包装类的区别,不可变对象的优势,以及如何安全地操作集合。

key word :

  • data type
  • mutability and mutable objects
  • static and dynamic type checking
  • Null references

Specific content as follows:
1 、Primitives&Object Reference Types P6
2、Boxed primitives(基本数据类型的包装类)
don’t use
包装类

Integer.valueOf()方法基于减少对象创建次数和节省内存的考虑,缓存了[-128,127]之间的数字。此数字范围内传参则直接返回缓存中的对象
解释valueOf缓存,必看

   Integer i01 = 2;
        int i02 =2;
        Integer i03 = Integer.valueOf(2);
        Integer i04 = new Integer (2);

        System.out.println(i01==i03);//true i01的转换过程就是i03,所以不建议使用 基本数据包装类
        System.out.println(i01==i02);//true
        //等号一边存在基本类型所以编译器后会把另一边的Integer对象拆箱成int型
        System.out.println(i03==i04);//false i03返回的是已缓存的对象的引用
        System.out.println(i04==i02);//true 拆箱 

上边代码的解释
上边文章中 补充对象引用
3、Mutability and Immutability P22
Mutability 修修补补
Immutability 另起炉灶 双圈 大量重复(for)
Risky example #1 P29

修复措施:复制性保护 P34

this.start=new Date(start.getTime());
this.end=new Date(end.getTime());
end.setyear(78)//设置年分成78年

解释上边复制性保护的例子

4、Arrays and Collections
Array List Map

  • 列表内容
    We cannot create a collection of primitive types
  • Declaration
List<String> cities; // a List of Strings
Set<Integer> numbers; // a Set of Integers
Map<String, Turtle> turtles; 

5、Mutation undermines an iterator P54
迭代器,删除元素的时候,删除完,下一个元素顶上去被删除的位置,接着就直接删除下一个,导致,顶包的那个得不到删除

Q:疑惑

6、Useful immutable types

  • 基本类型都是不可变的

  • List, Set,Map — are all mutable: ArrayList, HashMap, etc.
    但是可以使用 Collections.unmodifiableList

7、Null references

  • Primitives cannot be null
{ "cells": [ { "cell_type": "markdown", "id": "c6918234", "metadata": {}, "source": [ "# STUDENT VERSION — Variables, Expressions, and Conditional Execution — Interactive Lab\n", "\n", "Fill in each `# TODO` cell. Run with **Shift+Enter**." ] }, { "cell_type": "markdown", "id": "37755d3d", "metadata": {}, "source": [ "# Variables, Expressions, and Conditional Execution — Interactive Lab\n", "\n", "This notebook mirrors the in‑class activities. Work top‑to‑bottom. Each task has:\n", "- A short prompt\n", "- An empty code cell for you to complete\n", "- *(Optional)* hints/solutions hidden in expandable sections\n", "\n", "**Tip:** Run a cell with `Shift+Enter`.\n" ] }, { "cell_type": "markdown", "id": "4b136362", "metadata": {}, "source": [ "## Part 1 — Warm‑up: Indentation & Comments" ] }, { "cell_type": "markdown", "id": "49804a01", "metadata": {}, "source": [ "**Task 1.1**\n", "\n", "Fix the indentation and add a comment explaining what the code does.\n", "```python\n", "if True:\n", "print(\"Hello\")\n", "```\n" ] }, { "cell_type": "code", "execution_count": null, "id": "78471a1b", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "f90ba034", "metadata": {}, "source": [ " 💡 Hint " ] }, { "cell_type": "markdown", "id": "ceffdbca", "metadata": {}, "source": [ "## Part 2 — Variables & Dynamic Typing" ] }, { "cell_type": "markdown", "id": "2853f12e", "metadata": {}, "source": [ "**Task 2.1** — Reassign a variable to different types and print its type each time." ] }, { "cell_type": "code", "execution_count": null, "id": "510d0880", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "e50f6f18", "metadata": {}, "source": [ "## Part 3 — Expressions & Operators" ] }, { "cell_type": "markdown", "id": "19d97e98", "metadata": {}, "source": [ "**Task 3.1** — Temperature checker\n", "\n", "Write code that prints:\n", "- `\"Fever\"` if `temp > 37`\n", "- `\"Hypothermia\"` if `temp < 35`\n", "- otherwise `\"Normal\"`" ] }, { "cell_type": "code", "execution_count": null, "id": "d2402b9c", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "b1f69f7c", "metadata": {}, "source": [ "## Part 4 — Console I/O: `input()` and `print()`" ] }, { "cell_type": "markdown", "id": "2f61da76", "metadata": {}, "source": [ "**Task 4.1** — Ask for the user&#39;s age with `input()`, convert to `int`, and print a message about voting eligibility.\n", "\n", "*Note:* If running inside some hosted environments, interactive `input()` may not work. If so, set `age_str` manually." ] }, { "cell_type": "code", "execution_count": null, "id": "f26ce2f6", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "562253a5", "metadata": {}, "source": [ "## Part 5 — Lists vs Dictionaries" ] }, { "cell_type": "markdown", "id": "29c53e74", "metadata": {}, "source": [ "**Task 5.1 (List record)** — Use indexes to access fields.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0f5fa42a", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "0b44e365", "metadata": {}, "source": [ "**Task 5.2 (Dictionary record)** — Access values by key." ] }, { "cell_type": "code", "execution_count": null, "id": "bf92ed4f", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "dbeace2a", "metadata": {}, "source": [ "## Part 6 — Tuples & Sets" ] }, { "cell_type": "markdown", "id": "431ca9a4", "metadata": {}, "source": [ "**Task 6.1 (Set uniqueness)** — Observe how duplicates are removed." ] }, { "cell_type": "code", "execution_count": null, "id": "c14dc270", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "bb0e9fee", "metadata": {}, "source": [ "**Task 6.2 (Tuple immutability)** — Try to modify a tuple and capture the error." ] }, { "cell_type": "code", "execution_count": null, "id": "c2a63f31", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "f6265713", "metadata": {}, "source": [ "## Part 7 — Conditional Execution" ] }, { "cell_type": "markdown", "id": "668b4808", "metadata": {}, "source": [ "**Task 7.1** — Write a voting eligibility program using `if/elif/else` including a special case for age 17." ] }, { "cell_type": "code", "execution_count": null, "id": "0800b127", "metadata": {}, "outputs": [], "source": [ "# TODO: Complete this task here.\n" ] }, { "cell_type": "markdown", "id": "574ae6f7", "metadata": {}, "source": [ "## Part 8 — Quick Knowledge Check (no grading)" ] }, { "cell_type": "markdown", "id": "8131bac0", "metadata": {}, "source": [ "Answer in a new cell or in comments:\n", "1. Which data structure is **immutable**? (List / Tuple / Dict / Set)\n", "2. What operator checks equality? (`=` or `==`)\n", "3. Which keyword allows checking another condition after an `if`? (`elif` / `elseif`)\n", "4. Which function always returns a string? (`input` / `print`)\n" ] } ], "metadata": {}, "nbformat": 4, 上述代码的答案是什么?
09-13
以下是针对每个 `# TODO` 代码单元的完整答案和解析: --- ### **Task 1.1:修复缩进并添加注释** ```python # 如果条件为真,打印"Hello" if True: print("Hello") ``` **解析**: Python 对缩进敏感,`print` 需要缩进以表示属于 `if` 语句块。 --- ### **Task 2.1:重新赋值不同类型的变量并打印其类型** ```python x = 10 print(type(x)) # <class &#39;int&#39;> x = "Hello" print(type(x)) # <class &#39;str&#39;> x = 3.14 print(type(x)) # <class &#39;float&#39;> ``` **解析**: Python 是动态类型语言,同一个变量可以被赋值为不同的类型,`type()` 函数用于查看变量的类型。 --- ### **Task 3.1:温度检查器** ```python temp = 36 # 示例温度值 if temp > 37: print("Fever") elif temp < 35: print("Hypothermia") else: print("Normal") ``` **解析**: 使用 `if-elif-else` 结构进行条件判断,判断体温状态。 --- ### **Task 4.1:年龄输入与投票资格判断** ```python # 获取用户输入并转换为整数 age_str = input("Enter your age: ") age = int(age_str) # 判断投票资格 if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.") ``` **解析**: 使用 `input()` 获取用户输入,使用 `int()` 转换为整数,然后使用 `if-else` 进行判断。 --- ### **Task 5.1:列表记录(通过索引访问)** ```python record = ["Alice", 25, "Engineer"] print(record[0]) # 输出姓名 print(record[1]) # 输出年龄 print(record[2]) # 输出职业 ``` **解析**: 列表通过索引访问,索引从 `0` 开始。 --- ### **Task 5.2:字典记录(通过键访问)** ```python record = {"name": "Bob", "age": 30, "occupation": "Doctor"} print(record["name"]) # 输出姓名 print(record["age"]) # 输出年龄 print(record["occupation"]) # 输出职业 ``` **解析**: 字典通过键(key)访问对应的值(value)。 --- ### **Task 6.1:集合的唯一性** ```python my_set = {1, 2, 2, 3, 4, 4, 5} print(my_set) # 输出 {1, 2, 3, 4, 5} ``` **解析**: 集合自动去除重复元素,只保留唯一值。 --- ### **Task 6.2:元组不可变性** ```python my_tuple = (1, 2, 3) try: my_tuple[0] = 10 # 尝试修改元组 except TypeError as e: print(f"Error: {e}") ``` **解析**: 元组是不可变的,尝试修改会抛出 `TypeError` 异常。 --- ### **Task 7.1:投票资格判断(包含17岁特殊情况)** ```python age = int(input("Enter your age: ")) if age == 17: print("You are almost eligible to vote!") elif age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.") ``` **解析**: 使用 `if-elif-else` 结构,对 17 岁的情况做特殊处理。 --- ### **Part 8:快速知识检查答案** 1. **哪个数据结构是不可变的?** ✅ **答案:Tuple** 2. **哪个操作符用于检查相等性?** ✅ **答案:`==`** 3. **哪个关键字允许在 `if` 之后检查另一个条件?** ✅ **答案:`elif`** 4. **哪个函数始终返回字符串?** ✅ **答案:`input()`** --- ### ✅ 总结知识点 1. **条件执行** - 使用 `if`, `elif`, `else` 控制程序流程。 2. **数据结构特性** - 列表、字典可变;元组不可变;集合自动去重。 3. **类型转换与输入输出** - `input()` 返回字符串,需转换为其他类型;`print()` 输出内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值