《On Java 中文版 基础卷》阅读笔记 集合 24

《On Java 中文版 基础卷》阅读笔记 集合 24

12.7 LinkedList

和 ArrayList 一样,LinkedList 实现了基本的 List 接口。

但是与 ArrayList 相比,它在 List 中间执行插入和删除操作的效率更高,不过随机访问操作的表现要差一些。

LinkedList 还添加了一些可以使其用作栈、队列或双端队列 (deque) 的方法。

有些方法只是其他方法的别名,或者稍微有点不同的变种,只是为了特定使用场景而起了更常见的名字(特别是在 Queue 中)​。

  • getFirst() 和 element() 是完全相同的,它们都返回列表的头部(第一个元素),而并不移除它,如果 List 为空,则抛出NoSuchElementException。peek() 和这两个方法稍有不同,如果列表为空,它会返回 null。
  • removeFirst() 和 remove() 也是完全相同的,它们都会移除并返回列表的头,对于空列表则抛出 NoSuchElementException。poll() 稍有不同,如果列表为空,它会返回 null。
  • addFirst() 在列表的开头插入一个元素。
  • offer() 和 add() 以及 addLast() 相同,都是向列表的尾部插入一个元素。
  • removeLast() 移除并返回列表中的最后一个元素。

下面的示例演示了这些特性的基本异同点。它没有重复 ListFeatures.java 所演示的行为。

java 复制代码
package collections;

// collections/LinkedListFeatures.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import reflection.pets.*;
import java.util.*;

public class LinkedListFeatures {
  public static void main(String[] args) {
    LinkedList<Pet> pets = new LinkedList<>(new PetCreator().list(5));
    System.out.println(pets);
    // Identical:
    System.out.println(
        "pets.getFirst(): " + pets.getFirst());
    System.out.println(
        "pets.element(): " + pets.element());
    // Only differs in empty-list behavior:
    System.out.println("pets.peek(): " + pets.peek());
    // Identical; remove and return the first element:
    System.out.println(
        "pets.remove(): " + pets.remove());
    System.out.println(
        "pets.removeFirst(): " + pets.removeFirst());
    // Only differs in empty-list behavior:
    System.out.println("pets.poll(): " + pets.poll());
    System.out.println(pets);
    pets.addFirst(new Rat());
    System.out.println("After addFirst(): " + pets);
    pets.offer(new PetCreator().get());
    System.out.println("After offer(): " + pets);
    pets.add(new PetCreator().get());
    System.out.println("After add(): " + pets);
    pets.addLast(new Hamster());
    System.out.println("After addLast(): " + pets);
    System.out.println(
        "pets.removeLast(): " + pets.removeLast());
  }
}
/*
 * Output:
 * [Rat, Manx, Cymric, Mutt, Pug]
 * pets.getFirst(): Rat
 * pets.element(): Rat
 * pets.peek(): Rat
 * pets.remove(): Rat
 * pets.removeFirst(): Manx
 * pets.poll(): Cymric
 * [Mutt, Pug]
 * After addFirst(): [Rat, Mutt, Pug]
 * After offer(): [Rat, Mutt, Pug, Rat]
 * After add(): [Rat, Mutt, Pug, Rat, Rat]
 * After addLast(): [Rat, Mutt, Pug, Rat, Rat, Hamster]
 * pets.removeLast(): Hamster
 */

PetCreator.list() 的结果被传给 LinkedList 的构造器,用来填充这个列表。

如果观察一下 Queue 接口,会发现 element()、offer()、peek()、poll() 和 remove() 这些方法都被添加到了 LinkedList 中,

所以它就可以作为 Queue 的一个实现了。Queue 的完整示例将在本章稍后给出。

12.8 Stack

栈 (stack) 是一个 "后进先出" (LIFO) 的集合。它有时被称作下推栈,因为不管我们最后 "压入" 的是什么,它都会第一个 "弹出"​。

人们经常用放在弹簧支架上的餐盘来类比:最后放入的餐盘最先被拿出来使用。

Java 1.0 就提供了 Stack 类,结果这个类的设计非常糟糕。

不过因为要向后兼容,所以我们永远也无法摆脱 Java 过去的设计错误了。

Java 6 加入了 ArrayDeque,提供了直接实现栈功能的方法:

java 复制代码
package collections;

// collections/StackTest.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

public class StackTest {
  public static void main(String[] args) {
    Deque<String> stack = new ArrayDeque<>();
    for (String s : "My dog has fleas".split(" "))
      stack.push(s);
    while (!stack.isEmpty())
      System.out.print(stack.pop() + " ");
  }
}
/*
 * Output:
 * fleas has dog My
 */

尽管它在各方面的表现都像栈,但是我们仍然必须把它声明为 Deque。假设有一个名为 Stack 的类,这样逻辑就更清楚了:

java 复制代码
// onjava/Stack.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// A Stack class built with an ArrayDeque
package onjava;

import java.util.Deque;
import java.util.ArrayDeque;

public class Stack<T> {
  private Deque<T> storage = new ArrayDeque<>();

  public void push(T v) {
    storage.push(v);
  }

  public T peek() {
    return storage.peek();
  }

  public T pop() {
    return storage.pop();
  }

  public boolean isEmpty() {
    return storage.isEmpty();
  }

  @Override
  public String toString() {
    return storage.toString();
  }
}

这里使用泛型给出了最简单可行的一个 Stack 类的定义。

类名后面的 告诉编译器这是一个参数化的类型,并且类型参数为 T,当这个类被使用时,它会被替换为实际类型。

基本可以这样理解:我们定义了一个持有 T 类型对象的 Stack。Stack 是使用 ArrayDeque 实现的,它也持有 T 类型对象。

注意,push() 接受一个 T 类型的对象,而 peek() 和 pop() 返回一个 T 类型的对象。

peek() 方法用于提供栈顶元素,并不把它从栈顶移走,而 pop() 则移除并返回顶端元素。

如果只想要栈的行为,继承在这里就不合适了,因为这样会得到一个具有 ArrayDeque 的其余所有方法的类

(在进阶卷第 3 章中你会看到,这正是 Java 1.0 的设计者在创建 java.util.Stack 时所犯的错误)​。

使用组合,我们可以选择暴露哪些方法,以及如何为它们命名。

我们将使用与 StackTest.java 相同的代码来说明这个新的 Stack 类:

java 复制代码
package collections;

// collections/StackTest2.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import onjava.*;

public class StackTest2 {
  public static void main(String[] args) {
    Stack<String> stack = new Stack<>();
    for (String s : "My dog has fleas".split(" "))
      stack.push(s);
    while (!stack.isEmpty())
      System.out.print(stack.pop() + " ");
  }
}
/*
 * Output:
 * fleas has dog My
 */

要在自己的代码中使用这个 Stack,在创建对象时必须完整指定包名,或者(在创建类时)把类名改掉,

否则很可能会与 java.util 中的 Stack 冲突。

比如,如果我们在上面的代码示例中导入了 java.util.*,则必须使用包名来防止冲突:

java 复制代码
package collections;
// collections/StackCollision.java

// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class StackCollision {
  public static void main(String[] args) {
    onjava.Stack<String> stack = new onjava.Stack<>();
    for (String s : "My dog has fleas".split(" "))
      stack.push(s);
    while (!stack.isEmpty())
      System.out.print(stack.pop() + " ");
    System.out.println();
    java.util.Stack<String> stack2 = new java.util.Stack<>();
    for (String s : "My dog has fleas".split(" "))
      stack2.push(s);
    while (!stack2.empty())
      System.out.print(stack2.pop() + " ");
  }
}
/*
 * Output:
 * fleas has dog My
 * fleas has dog My
 */

虽然已经有 java.util.Stack 存在,但是 ArrayDeque 带来了一个更好的 Stack,所以更为可取。

也可以使用显式导入来控制首选的 Stack 实现:

java 复制代码
import onjava.Stack

这样任何对 Stack 的引用就都会选择 onjava 版本,如果要选择 java.util.Stack,则必须使用全限定名。

12.9 Set

Set 中不允许出现重复的对象值。对于等价对象的实例,如果尝试添加多个,那么 Set 会阻止。

Set 最常见的用法就是测试成员身份,所以我们可以很轻松地询问某个对象是否在 Set 中。

正因如此,查找通常是 Set 最重要的操作,所以我们通常会选择一个 HashSet 的实现,它针对快速查找做了优化。

Set 与 Collection 有相同的接口,所以不像 List 的两种类型那样有额外的功能。

相反,Set 就是一个 Collection,只是行为不同。​(这就是继承和多态的理想使用场景:表现不同的行为。​)

Set 根据对象的 "值" 来确定成员身份,更复杂的主题会在进阶卷第 3 章中介绍。

下面的示例代码使用了一个持有 Integer 对象的 HashSet。

java 复制代码
package collections;// collections/SetOfInteger.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;

public class SetOfInteger {
    public static void main(String[] args) {
        Random rand = new Random(47);
        Set<Integer> intset = new HashSet<>();
        for (int i = 0; i < 10000; i++)
            intset.add(rand.nextInt(30));
        System.out.println(intset);
    }
}
/* Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
*/

我们生成了 10 000 个 0~29 范围内的数,并将其添加到这个 Set 中,所以不难想象,每个值都会重复很多次。然而我们看到的是,每个值都只有一个实例出现在了结果中。

在早期的 Java 版本中,HashSet 输出的顺序没有明显的规律可循。

HashSet 使用哈希来提升速度,进阶卷第 3 章中将介绍哈希。

HashSet 所维护的顺序与 TreeSet 或 LinkedHashSet 不同,因为每种实现存储元素的方式不同。

TreeSet 将元素排序存储在红黑树数据结构中,而 HashSet 使用的是哈希函数。

LinkedHashSet 也使用哈希来提升查找速度,但看起来是使用链表按照插入顺序来维护元素的。

显然,哈希算法变了,现在示例代码中输出的 Integer 是有序的。然而我们不应该依赖这种行为。

java 复制代码
package collections;// collections/SetOfString.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;

public class SetOfString {
    public static void main(String[] args) {
        Set<String> colors = new HashSet<>();
        for (int i = 0; i < 100; i++) {
            colors.add("Yellow");
            colors.add("Blue");
            colors.add("Red");
            colors.add("Red");
            colors.add("Orange");
            colors.add("Yellow");
            colors.add("Blue");
            colors.add("Purple");
        }
        System.out.println(colors);
    }
}
/* Output:
[Red, Yellow, Blue, Purple, Orange]
*/

这些 String 对象看上去并没有排序。如果要给输出结果排序,一种方法是使用 TreeSet 来代替 HashSet:

java 复制代码
package collections;// collections/SortedSetOfString.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;

public class SortedSetOfString {
    public static void main(String[] args) {
        Set<String> colors = new TreeSet<>();
        for (int i = 0; i < 100; i++) {
            colors.add("Yellow");
            colors.add("Blue");
            colors.add("Red");
            colors.add("Red");
            colors.add("Orange");
            colors.add("Yellow");
            colors.add("Blue");
            colors.add("Purple");
        }
        System.out.println(colors);
    }
}
/* Output:
[Blue, Orange, Purple, Red, Yellow]
*/

最常见的操作之一是使用 contains() 来测试 Set 成员身份,但也有像维恩图这样的操作,你可能在小学就学过:

java 复制代码
package collections;// collections/SetOperations.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;

public class SetOperations {
    public static void main(String[] args) {
        Set<String> set1 = new HashSet<>();
        Collections.addAll(set1,
                "A B C D E F G H I J K L".split(" "));
        set1.add("M");
        System.out.println("H: " + set1.contains("H"));
        System.out.println("N: " + set1.contains("N"));
        Set<String> set2 = new HashSet<>();
        Collections.addAll(set2, "H I J K L".split(" "));
        System.out.println(
                "set2 in set1: " + set1.containsAll(set2));
        set1.remove("H");
        System.out.println("set1: " + set1);
        System.out.println(
                "set2 in set1: " + set1.containsAll(set2));
        set1.removeAll(set2);
        System.out.println(
                "set2 removed from set1: " + set1);
        Collections.addAll(set1, "X Y Z".split(" "));
        System.out.println(
                "'X Y Z' added to set1: " + set1);
    }
}
/* Output:
H: true
N: false
set2 in set1: true
set1: [A, B, C, D, E, F, G, I, J, K, L, M]
set2 in set1: false
set2 removed from set1: [A, B, C, D, E, F, G, M]
'X Y Z' added to set1: [A, B, C, D, E, F, G, M, X, Y,
Z]
*/

方法的名称都是不言自明的,而且 JDK 文档中还有更多介绍。

产生一个没有重复元素的列表有时非常有用。

例如,假设我们想列出上面的 SetOperations.java 文件中的所有单词,

使用本书后面会介绍的 java.nio.file.Files.readAllLines() 方法,可以打开一个文件,将内容读入到一个 List 中,每个 String 是输入文件中的一行:

java 复制代码
package collections;// collections/UniqueWords.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;
import java.nio.file.*;

public class UniqueWords {
    public static void
    main(String[] args) throws Exception {
        List<String> lines = Files.readAllLines(
                Paths.get("SetOperations.java"));
        Set<String> words = new TreeSet<>();
        for (String line : lines)
            for (String word : line.split("\\W+"))
                if (word.trim().length() > 0)
                    words.add(word);
        System.out.println(words);
    }
}
/* Output:
[A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K,
L, M, N, Output, Set, SetOperations, String, System, X,
Y, Z, add, addAll, added, args, class, collections,
contains, containsAll, false, from, import, in, java,
main, new, out, println, public, remove, removeAll,
removed, set1, set2, split, static, to, true, util,
void]
*/

我们依次处理文件中的每一行,以正则表达式 \W+ 为参数,使用 String.split() 将其分解为单词。

这个正则表达式意味着会在一个或多个 (+) 非文字字母上分隔。正则表达式会在第 18 章介绍。

所产生的每个单词都被加到了 words 这个 Set 中。因为它是 TreeSet,所以结果是有序的。

这里的排序是按字典顺序进行的,所以大写字母和小写字母会被划分到不同的组中。

如果想按照字母顺序排序,

可以把 String.CASE_INSENSITIVE_ORDER 这个 Comparator(比较器是用来建立顺序关系的对象)传递给TreeSet 的构造器:

java 复制代码
package collections;// collections/UniqueWordsAlphabetic.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Producing an alphabetic listing

import java.util.*;
import java.nio.file.*;

public class UniqueWordsAlphabetic {
    public static void
    main(String[] args) throws Exception {
        List<String> lines = Files.readAllLines(
                Paths.get("SetOperations.java"));
        Set<String> words =
                new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        for (String line : lines)
            for (String word : line.split("\\W+"))
                if (word.trim().length() > 0)
                    words.add(word);
        System.out.println(words);
    }
}
/* Output:
[A, add, addAll, added, args, B, C, class, collections,
contains, containsAll, D, E, F, false, from, G, H,
HashSet, I, import, in, J, java, K, L, M, main, N, new,
out, Output, println, public, remove, removeAll,
removed, Set, set1, set2, SetOperations, split, static,
String, System, to, true, util, void, X, Y, Z]
*/

Comparator 将在第 21 章详细介绍。

12.10 Map

能够将对象映射到其他对象,这是解决编程问题的一种强有力的方法。

例如,考虑编写一个程序,来检测 Java 的 Random 类的随机性。

理想情况下,Random 可以产生完美的数值分布,

但为了验证这一点,我们必须生成大量的随机数,然后计算落入不同区间的数的数量。

Map 很容易解决这个问题。这里键就是 Random 生成的数,值就是该数出现的次数:

java 复制代码
package collections;// collections/Statistics.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Simple demonstration of HashMap

import java.util.*;

public class Statistics {
    public static void main(String[] args) {
        Random rand = new Random(47);
        Map<Integer, Integer> m = new HashMap<>();
        for (int i = 0; i < 10000; i++) {
            // Produce a number between 0 and 20:
            int r = rand.nextInt(20);
            Integer freq = m.get(r);               // [1]
            m.put(r, freq == null ? 1 : freq + 1);
        }
        System.out.println(m);
    }
}
/* Output:
{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519,
7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506,
14=477, 15=497, 16=533, 17=509, 18=478, 19=464}
*/

1 自动装箱机制将随机生成的 int 转换为可用于 HashMap 的 Integer 引用(我们不能在集合类中使用基本类型 )​。

如果集合中尚不存在该键,get() 返回 null(意味着该数字是第一次被找到)​。

否则,get() 会返回与该键关联的 Integer 值,并将其增加 1

(自动装箱简化了表达式,但事实上 int 和 Integer 之间的转换仍然是要进行的)​。

接下来,我们将使用一个 String 描述信息来查找 Pet 对象。

这里也演示了如何使用 containsKey() 和 containsValue() 来检查一个 Map,看看其中是否包含某个键或某个值。

java 复制代码
package collections;// collections/PetMap.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import reflection.pets.*;

import java.util.*;

public class PetMap {
    public static void main(String[] args) {
        Map<String, Pet> petMap = new HashMap<>();
        petMap.put("My Cat", new Cat("Molly"));
        petMap.put("My Dog", new Dog("Ginger"));
        petMap.put("My Hamster", new Hamster("Bosco"));
        System.out.println(petMap);
        Pet dog = petMap.get("My Dog");
        System.out.println(dog);
        System.out.println(petMap.containsKey("My Dog"));
        System.out.println(petMap.containsValue(dog));
    }
}
/* Output:
{My Dog=Dog Ginger, My Cat=Cat Molly, My
Hamster=Hamster Bosco}
Dog Ginger
true
true
*/

类似于数组和 Collection, Map 也很容易扩展为多维;

我们可以创建一个值为 Map 的 Map(那些 Map 的值可以是其他集合,甚至是其他 Map)​。

因此,将集合组合起来快速生成强大的数据结构非常容易。

例如,假设要记录拥有多个宠物的人,我们所需要的只是一个 Map<Person, List>:

java 复制代码
// collections/MapOfList.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java collections.MapOfList}
package collections;

import reflection.pets.*;

import java.util.*;

public class MapOfList {
    public static final Map<Person, List<? extends Pet>>
            petPeople = new HashMap<>();

    static {
        petPeople.put(new Person("Dawn"),
                Arrays.asList(
                        new Cymric("Molly"),
                        new Mutt("Spot")));
        petPeople.put(new Person("Kate"),
                Arrays.asList(new Cat("Shackleton"),
                        new Cat("Elsie May"), new Dog("Margrett")));
        petPeople.put(new Person("Marilyn"),
                Arrays.asList(
                        new Pug("Louie aka Louis Snorkelstein Dupree"),
                        new Cat("Stanford"),
                        new Cat("Pinkola")));
        petPeople.put(new Person("Luke"),
                Arrays.asList(
                        new Rat("Fuzzy"), new Rat("Fizzy")));
        petPeople.put(new Person("Isaac"),
                Arrays.asList(new Rat("Freckly")));
    }

    public static void main(String[] args) {
        System.out.println("People: " + petPeople.keySet());
        System.out.println("Pets: " + petPeople.values());
        for (Person person : petPeople.keySet()) {
            System.out.println(person + " has:");
            for (Pet pet : petPeople.get(person))
                System.out.println("    " + pet);
        }
    }
}
/* Output:
People: [Person Dawn, Person Kate, Person Isaac, Person
Marilyn, Person Luke]
Pets: [[Cymric Molly, Mutt Spot], [Cat Shackleton, Cat
Elsie May, Dog Margrett], [Rat Freckly], [Pug Louie aka
Louis Snorkelstein Dupree, Cat Stanford, Cat Pinkola],
[Rat Fuzzy, Rat Fizzy]]
Person Dawn has:
    Cymric Molly
    Mutt Spot
Person Kate has:
    Cat Shackleton
    Cat Elsie May
    Dog Margrett
Person Isaac has:
    Rat Freckly
Person Marilyn has:
    Pug Louie aka Louis Snorkelstein Dupree
    Cat Stanford
    Cat Pinkola
Person Luke has:
    Rat Fuzzy
    Rat Fizzy
*/

Map 可以返回一个包含其所有键的 Set,包含其所有值的 Collection,或者包含其键值对的 Set。

keySet() 会生成一个 Set,包含 petPeople 中的所有键,我们在 for-in 语句中用它来遍历整个 Map。

12.11 新特性:记录 (record) 类型

一旦接触过 Map,很容易对所有可以使用它的方式感到兴奋。

不过有一个障碍。要让一个类的对象可以用作 Map(或 Set)中的键,我们必须为这个类定义两个函数:equals() 和 hashCode()。

写对很难,如果以后要修改这个类的话,还很容易破坏它们,这就使得将这样的对象用作 Map 或 Set 中的键更难了。

JDK 16 最终增加了 record 关键字。record 定义的是希望成为数据传输对象(也叫数据载体)的类。

当使用 record 关键字时,编译器会自动生成:

  • 不可变的字段
  • 一个规范的构造器
  • 每个元素都有的访问器方法
  • equals()
  • hashCode()
  • toString()

通过如下示例,我们可以看到每个功能:

java 复制代码
package collections;// collections/BasicRecord.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

import java.util.*;

record Employee(String name, int id) {
}

public class BasicRecord {
    public static void main(String[] args) {
        var bob = new Employee("Bob Dobbs", 11);
        var dot = new Employee("Dorothy Gale", 9);
        // bob.id = 12; // Error:
        // id has private access in Employee
        System.out.println(bob.name()); // Accessor
        System.out.println(bob.id()); // Accessor
        System.out.println(bob); // toString()
        // Employee works as the key in a Map:
        var map = Map.of(bob, "A", dot, "B");
        System.out.println(map);
    }
}
/* Output:
Bob Dobbs
11
Employee[name=Bob Dobbs, id=11]
{Employee[name=Dorothy Gale, id=9]=B, Employee[name=Bob Dobbs, id=11]=A}
*/

对于大多数 record,我们只需给它一个名字和参数,不需要在定义体中添加任何东西。

这将自动创建规范的构造器,就是在 main() 中的前两行代码调用的那个。

它还创建了内部的 private final 字段 name 和 id。构造器会根据其参数列表来初始化这些字段。

不能向 record 中添加字段,只能将其定义在头部。不过可以加入静态的方法、字段和初始化器。

通过 record 的参数列表定义的每个属性都会自动获得自己的访问器,

如我们在调用中看到的 bob.name() 和 bob.id()。

Java 的设计者们没有继续使用过时的 JavaBean 中的实践------把访问器叫作 getName() 和 getId(),我个人很欣赏这一点。

从输出可以看到,record 还创建了一个不错的 toString() 方法。因为 record 会创建合理定义的 hashCode() 和 equals(),

所以 Employee 可以用作一个 Map 中的键。当这个 Map 被显示时,toString() 会生成可读性非常好的结果。

如果以后决定增加、减少或改变已定义的 record 中的一个字段,Java 可以确保其结果仍能正常工作。

这种可修改性是使 record 价值如此之大的原因之一。

record 可以定义方法,但是这些方法只能读取字段,因为这些字段会自动成为最终变量:

java 复制代码
package collections;// collections/FinalFields.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

import java.util.*;

record FinalFields(int i) {
    int timesTen() {
        return i * 10;
    }
    // void tryToChange() { i++; } // Error:
    // cannot assign a value to final variable i
}

记录可以由其他对象组成,包括其他记录:

java 复制代码
package collections;// collections/ComposedRecord.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

record Company(Employee[] e) {
}

// class Conglomerate extends Company {}
// error: cannot inherit from final Company

我们不能继承 record,因为它隐含为 final 的(而且不能为 abstract 的)​。

此外,record 也不能继承其他类。然而,record 可以实现 interface:

java 复制代码
package collections;// collections/ImplementingRecord.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

interface Star {
    double brightness();

    double density();
}

record RedDwarf(double brightness) implements Star {
    @Override
    public double density() {
        return 100.0;
    }
}

编译器会强制我们提供一个 density() 的定义,但是它并不会因为 brightness() 报错。

这是因为,record 会为其 brightness 参数生成一个访问器,而这个访问器正好匹配接口 Star 中的 brightness()。

record 可以嵌套在类中,也可以在某个方法内定义:

java 复制代码
package collections;// collections/NestedLocalRecords.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

public class NestedLocalRecords {
    record Nested(String s) {
    }

    void method() {
        record Local(String s) {
        }
    }
}

嵌套和局部的 record 隐含都是静态的。

尽管规范的构造器会被根据 record 的参数自动创建出来,

但是我们可以使用一个紧凑构造器 (compact constructor) 来添加构造器行为,它看上去像一个构造器,但是没有参数列表:

java 复制代码
package collections;// collections/CompactConstructor.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

record Point(int x, int y) {
    void assertPositive(int val) {
        if (val < 0)
            throw new IllegalArgumentException("negative");
    }

    Point { // Compact: No parameter list
        assertPositive(x);
        assertPositive(y);
    }
}

紧凑构造器通常用于验证参数。也可以修改字段的初始化值:

java 复制代码
package collections;// collections/PlusTen.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

record PlusTen(int x) {
    PlusTen {
        x += 10;
    }

    // Adjustment to field can only happen in
    // the constructor. Still not legal:
    // void mutate() { x += 10; }
    public static void main(String[] args) {
        System.out.println(new PlusTen(10));
    }
}
/* Output:
PlusTen[x=20]
*/

尽管这看起来好像是在修改 final 值,但是编译器实际上会为 x 创建一个中间的占位符,然后在构造器的最后执行一次赋值,

将结果赋值给 this.x。

如果有必要,我们可以使用普通构造器语法替换掉规范构造器:

java 复制代码
package collections;// collections/NormalConstructor.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

record Value(int x) {
    Value(int x) { // With the parameter list
        this.x = x; // Must explicitly initialize
    }
}

这看起来有点奇怪。构造器必须精确复制这个 record 的签名,包括标识符的名字------我们不能像 Value(int initValue) 这样定义它。

此外,record Value(int x) 会生成一个名为 x 的 final 字段,当使用非紧凑构造器时,这个字段不会被初始化,

所以如果这个构造器不初始化 this.x,则会出现编译时错误。

幸运的是,只有极少数情况才会用到 record 的这种普通构造器。

如果一定要写一个构造器,那几乎总是紧凑形式,会为我们处理字段的初始化。

要复制一个 record,必须显式地将所有字段都传给其构造器:

java 复制代码
package collections;// collections/CopyRecord.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 16

record R(int a, double b, char c) {
}

public class CopyRecord {
    public static void main(String[] args) {
        var r1 = new R(11, 2.2, 'z');
        var r2 = new R(r1.a(), r1.b(), r1.c());
        System.out.println(r1.equals(r2));
    }
}
/* Output:
true
*/

创建 record,编译器会为其生成 equals() 方法,这个方法可以确保副本与其原来的对象是等同的。

在类似结构的用处在其他语言中得到证明之后,record 加到了 Java 中。

加入 record 之后,所消除的样板代码和错误的数量相当显著。

record 也提升了代码的可读性,而且过去程序员会相当抗拒加入实现类似功能的类,但是现在他们会毫不犹豫地加入 record 类型。

相关推荐
小小测试开发15 分钟前
rsync 源路径少一个斜杠,--delete 删的就不是你以为的那一层
java·前端·数据库·人工智能
智购科技无人售货机工厂店1 小时前
自动售货机刷脸支付集成实战:活体检测与合规门槛~YH
java·服务器·前端·科技·零售
随流寻影1 小时前
利用 C++ 实现快速排序及三种优化
开发语言·c++
默 语1 小时前
【HarmonyOS7】ArkTS通用属性实战(六):组件级像素取整 pixelRound
开发语言
Nazarick2 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
西西弗Sisyphus2 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 指针与内存地址(2)
开发语言·c++
宿州派大星2 小时前
Python 音视频处理流水线:视频分离音频 + 讯飞转写 + 星火大模型解析(附完整代码与踩坑指南)
开发语言·python·音视频
黑色的白兔No12 小时前
若依平台cloud版本搭建
java·spring cloud·微服务·nacos·vue·若依
烟烟Abandon3 小时前
FFmpeg开发基础之 C 语言编译器
c语言·开发语言·ffmpeg