Java 中 Pair 类的五种替代方案

该文章已生成可运行项目,

Pair 是一个容器,用于存储两个对象的元组。Java 并没有真正提供 Pair 类的任何实现。这篇文章将讨论 Java 中 Pair 类的各种替代方案。

Pair 通常用于一起跟踪两个对象。它包含两个字段,通常称为firstand second,能够存储任何内容。尽管firstsecond字段之间没有任何有意义的关系,但程序员经常会错过 Java 中的这个功能。

在上一篇文章中,我们讨论了如何在 Java 中实现我们自己的 Pair 类。这篇文章将讨论 Java 中可用的解决方法来填补所需的空白,如下所述:

1. 使用Map.Entry<K,V>界面

我们可以在 Java 中使用Map.Entry<K,V>接口,类似于std::pairC++ 中的接口。这是具有代表键值对的有意义名称的绝佳示例。

为了创建表示从指定键到指定值的映射的条目,Java 提供了该Map.Entry接口的两个具体实现,即AbstractMap.SimpleEntryAbstractMap.SimpleImmutableEntry

 

 
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
30
31
32
33
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
class Pair
{
    // Return a map entry (key-value pair) from the specified values
    public static <T, U> Map.Entry<T, U> of(T first, U second) {
        return new AbstractMap.SimpleEntry<>(first, second);
    }
}
 
class Main
{
    // Implement Pair class in Java using `Map.Entry`
    public static void main(String[] args)
    {
        Set<Map.Entry<String, Integer>> entries = new HashSet<>();
 
        entries.add(Pair.of("Java", 50));
        entries.add(Pair.of("C++", 30));
 
        System.out.println(entries);
 
        // runs in Java 8 and above only
        entries.forEach(entry -> {
            if (entry.getKey().equals("Java")) {
                System.out.println(entry.getValue());
            }
        });
    }
}

 

下载  运行代码

输出:

[Java=50,C++=30]
50

2. 使用 Java 8 – javafx.util.Pair

终于,经过漫长的等待,Java 8 的package.json 中添加了一个Pair<K,V> 类javafx.util。类表示键值对,并支持像非常基本的操作getKey()getValue()hashCode()equals(java.lang.Object o),和toString()并具有继承一些方法java.lang.Object类。嗯,有总比没有好,是吧?

 

 
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
import javafx.util.Pair;
 
import java.util.ArrayList;
import java.util.List;
 
class Main
{
    // Demonstrate `javafx.util.Pair` class introduced in Java 8 and above
    public static void main(String[] args)
    {
        List<Pair<String, Integer>> entries = new ArrayList<>();
 
        entries.add(new Pair<>("C", 20));
        entries.add(new Pair<>("C++", 30));
 
        // print first pair using `getKey()` and `getValue()` method
 
        System.out.println("{" + entries.get(0).getKey() + ", " +
                            entries.get(0).getValue() + "}");
 
        // print second pair using `getKey()` and `getValue()` method
 
        System.out.println("{" + entries.get(1).getKey() + ", " +
                            entries.get(1).getValue() + "}");
    }
}

 

下载代码

输出:

{C, 20}
{C++, 30}

3. 使用 Apache Commons Lang

Apache Commons Lang 库还提供了一个Pair<L,R> 实用程序类,其元素是leftright。它被定义为抽象并实现了Map.Entry接口,其中键是left,值是right

它具有Pair.of()可用于从指定的对象对中获取不可变对的方法。它的子类MutablePair是可变的,而不可变的ImmutablePair。但是,存储在ImmutablePaircan中的对象的类型本身可能是可变的。

 

 
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
 
import java.util.ArrayList;
import java.util.List;
 
class Main
{
    // Demonstrate Pair class provided Apache Commons Library in Java
    public static void main(String[] args)
    {
        List<Pair<String, Integer>> entries = new ArrayList<>();
 
        entries.add(new MutablePair<>("C", 20));        // using `MutablePair`
        entries.add(new ImmutablePair<>("C++", 30));    // using `ImmutablePair`
        entries.add(Pair.of("Java", 50));               // using `Pair.of()`
 
        System.out.println(entries);
 
        // 1. The first pair is mutable
        Pair<String, Integer> pair = entries.get(0);
        pair.setValue(100);     // works fine
 
        // printing pair using `getKey()` and `getValue()` method
        System.out.println(pair.getKey() + ", " + pair.getValue());
 
        // 2. The second pair is immutable
        pair = entries.get(1);
        try {
            pair.setValue(100); // runtime error
        }
        catch (UnsupportedOperationException ex) {
            System.out.println("UnsupportedOperationException thrown");
        }
 
        // printing pair using `getLeft()` and `getRight()` method
        System.out.println(pair.getLeft() + ", " + pair.getRight());
 
        // 3. The third pair is also immutable
        pair = entries.get(2);
        try {
            pair.setValue(100); // runtime error
        }
        catch (UnsupportedOperationException ex) {
            System.out.println("UnsupportedOperationException thrown");
        }
        System.out.println(pair.getLeft() + ", " + pair.getRight());
    }
}

 

下载代码

输出:

[(C,20), (C++,30), (Java,50)]
C, 100
UnsupportedOperationException 抛出
C++, 30
UnsupportedOperationException 抛出
Java, 50

4. 使用JavaTuples

Javatuples是另一个处理元组的著名且简单的 Java 库。它提供了一组Java从一到十个元素的元组类。为了达到我们的目的,我们可以使用Pair<A,B> 类

 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.javatuples.Pair;
import java.util.ArrayList;
import java.util.List;
 
class Main
{
    // Demonstrate Pair class provided by `JavaTuples` Library in Java
    public static void main(String[] args)
    {
        List<Pair<String, Integer>> pairs = new ArrayList<>();
 
        pairs.add(Pair.with("Java", 50));    // using `Pair.with()`
        pairs.add(new Pair<>("C++", 30));    // using constructors
 
        // print first pair using `getValue0()` and `getValue1()` method
        System.out.println("{" + pairs.get(0).getValue0() + ", " +
                            pairs.get(0).getValue1() + "}");
 
        // print second pair using `getValue0()` and `getValue1()` method
        System.out.println("{" + pairs.get(1).getValue0() + ", " +
                            pairs.get(1).getValue1() + "}");
    }
}

 

下载代码

输出:

{Java,50}
{C++,30}

五、使用Collections.singletonMap()方法

另一种方法是Collections.singletonMap()在 Java 中使用类似于Map.Entry<K,V>前面讨论的 。它返回一个不可变的单例映射,只包含指定的键值对映射,可以将其视为 Pair。

 

 
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
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
class Pair
{
    // Return an immutable singleton map containing only the specified
    // key-value pair mapping
    public static <T, U> Map<T, U> of(T first, U second) {
        return Collections.singletonMap(first, second);
    }
}
 
class Tuple
{
    // Implement Pair class in Java using `Collections.singletonMap()`
    public static void main(String[] args)
    {
        Set<Map<String, Integer>> entries = new HashSet<>();
 
        entries.add(Pair.of("Java", 50));
        entries.add(Pair.of("C++", 30));
 
        System.out.println(entries);
    }
}

 

下载  运行代码

输出:

[{Java=50},{C++=30}]

 
最后,在Android项目中,我们可以使用Android SDK提供的android.util.Pair类。

这就是PairJava 类的替代方案。

本文章已经生成可运行项目
### ESP01烧录教程及相关指南 ESP01 是一款基于 ESP8266 的 Wi-Fi 模块,广泛应用于物联网设备开发中。以下是关于如何成功完成 ESP01 固件烧录的过程说明。 #### 工具准备 为了实现 ESP01 的固件刷入操作,需准备好以下工具和材料: - **硬件部分**:USB 转串口模块(支持 CH340 或 CP2102)、ESP01 模块、杜邦线若干。 - **软件部分**:电脑端安装驱动程序(CH340 驱动或 CP2102 驱动),以及用于固件烧写的工具 `esptool.py`[^1]。 #### 环境配置与连接设置 在开始之前,请确认 USB 转串口模块已正确识别,并分配有对应的 COM 口编号。随后按照如下方式连接 ESP01 和 USB-TTL 模块: | ESP01 Pin | USB-TTL Pin | |-----------|-------------| | GND | GND | | TX | RX | | RX | TX | | VCC | 3.3V (切勿接5V!) | 注意,在实际烧写过程中还需要短接 GPIO0 至 GND 来进入下载模式[^2]。 #### 使用 esptool 进行固件烧录 确保 Python 环境已经搭建完毕之后,可以通过 pip 安装最新版本的 esptool 库: ```bash pip install --upgrade esptool ``` 执行擦除芯片命令前先清空原有数据以防冲突发生: ```bash esptool.py --port COMX erase_flash ``` 接着上传目标固件文件至指定地址(通常为偏移量 0x0000),假设本地路径下存在名为 firmware.bin 的二进制镜像,则运行下面这条语句即可完成整个流程: ```bash esptool.py --chip esp8266 --port COMX write_flash 0x0000 firmware.bin ``` 以上步骤均应严格按照官方文档指示逐步实施以减少失败几率。 #### 常见问题排查技巧 如果遇到诸如“Failed to connect”之类的提示信息时,可以尝试调整波特率参数或者重新插拔设备来改善接触状况;另外也要留意供电电压是否稳定充足等问题。 对于希望进一步了解 MQTT 协议通信机制的朋友来说,可参考另一份资料学习如何利用 AT 指令集构建简单的发布订阅模型实例[^3]。
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值