分析Pair类以及其简单使用

329 阅读2分钟

源码

public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
    private static final long serialVersionUID = 4954918890077093841L;

    public Pair() {
    }

    public static <L, R> Pair<L, R> of(L left, R right) {
        return new ImmutablePair(left, right);
    }

    public abstract L getLeft();

    public abstract R getRight();

    public final L getKey() {
        return this.getLeft();
    }

    public R getValue() {
        return this.getRight();
    }

    public int compareTo(Pair<L, R> other) {
        return (new CompareToBuilder()).append(this.getLeft(), other.getLeft()).append(this.getRight(), other.getRight()).toComparison();
    }

    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        } else if (!(obj instanceof Map.Entry)) {
            return false;
        } else {
            Map.Entry<?, ?> other = (Map.Entry)obj;
            return ObjectUtils.equals(this.getKey(), other.getKey()) && ObjectUtils.equals(this.getValue(), other.getValue());
        }
    }

    public int hashCode() {
        return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^ (this.getValue() == null ? 0 : this.getValue().hashCode());
    }

    public String toString() {
        return "" + '(' + this.getLeft() + ',' + this.getRight() + ')';
    }

    public String toString(String format) {
        return String.format(format, this.getLeft(), this.getRight());
    }
}

解析

这类 Pair 是 Apache Commons Lang 3 中的一个抽象类,用于表示一对值的数据结构。使用 Pair 时: 当你只需存储两个相关的值,并不需要复杂的键值对集合时,Pair 是一个简单而轻量的选择。下面是对该类的 API 文档进行简要总结:

类名:Pair<L, R>

  • 继承关系:
    • Map.Entry<L, R>:实现了 Map.Entry 接口,可以用于与其他集合框架交互。
    • Comparable<Pair<L, R>>:实现了 Comparable 接口,可以用于比较两个 Pair 的大小。
    • Serializable:实现了 Serializable 接口,支持序列化。
  • 字段:
    • serialVersionUID:序列化版本号。
    • EMPTY_ARRAY:空数组,用于表示空的 Pair 数组。
  • 构造方法:
    • Pair():无参构造方法。
  • 静态方法:
    • emptyArray():返回一个空的 Pair 数组。
    • of(L left, R right):通过指定的左值和右值创建一个 Pair 对象。
    • of(Map.Entry<L, R> pair):通过给定的 Map.Entry 创建一个 Pair 对象。
  • 实例方法:
    • getLeft():获取左值。
    • getRight():获取右值。
    • getValue():获取右值(实现 Map.Entry 接口)。
    • getKey():获取左值(实现 Map.Entry 接口)。
    • compareTo(Pair<L, R> other):比较两个 Pair 的大小。
    • equals(Object obj):判断两个对象是否相等。
    • hashCode():计算哈希值。
    • toString():返回表示该 Pair 对象的字符串,形如 "(left, right)"。
    • toString(String format):使用指定的格式返回表示该 Pair 对象的字符串。

内部类:PairAdapter<L, R>

  • 静态内部类:
    • PairAdapter:实现了 Pair 的适配器,用于表示空的 Pair 对象。
    • getLeft():返回 null
    • getRight():返回 null
    • setValue(R value):返回 null

使用

导入依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version> <!-- 使用当前版本或更高版本 -->
</dependency>

使用

import org.apache.commons.lang3.tuple.Pair;

public class PairExample {

    public static void main(String[] args) {
        // 创建一个 Pair 对象
        Pair<String, Integer> pair = Pair.of("John", 25);

        // 获取 Pair 中的元素
        String name = pair.getLeft();
        Integer age = pair.getRight();

        // 输出元素的值
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);

        // 修改 Pair 中的元素
        Pair<String, Integer> updatedPair = Pair.of("Alice", 30);

        // 获取修改后的元素
        String updatedName = updatedPair.getLeft();
        Integer updatedAge = updatedPair.getRight();

        // 输出修改后的元素的值
        System.out.println("Updated Name: " + updatedName);
        System.out.println("Updated Age: " + updatedAge);
    }
}

优势分析:

不难看出Pair继承Map,相对Map而言,Pair有以下优势:

  1. 轻量: Pair 类是一个简单的元组结构,用于表示两个相关联的值。它相对轻量,没有 Map 中的复杂性。
  2. 简洁: 当你只需要存储两个值,而不需要使用键值对的概念时,使用 Pair 可以更为简洁。