Java的Pair类的用法以及替代方案

Pair介绍

Java8开始新添了Pair类,在javafx.util包中。目前主要作用是同时跟踪两个毫无关联的对象,比如,当你想用一个接口返回两个对象时,Pair就很有用。

用法

Pair用法很简单,直接构造Pair<K,V>对象,它只提供获取K和V的方法,没有更改的方法,因此它是固定的键值对。

Pair<String, Integer> pair = new Pair<>("pair", 1);
System.out.println(pair.getKey());
System.out.println(pair.getValue());

替代方案

1、AbstractMap.SimpleEntry 和 AbstractMap.SimpleImmutableEntry
SimpleEntry定义在抽象类AbstractMap里面,其比Pair多了可以改变V的值

AbstractMap.SimpleEntry<Integer, String> entry
	= new AbstractMap.SimpleEntry<>(1, "one");
System.out.println(entry.getKey());
System.out.println(entry.getValue());
entry.setValue("two");
System.out.println(entry.getValue());

另外SimpleImmutableEntry是AbstractMap 类包含的一个嵌套类,表示不可变配对,等效于Pair,如果调用了setValue()方法,将会抛出UnsupportedOperationException异常

AbstractMap.SimpleImmutableEntry<Integer, String> entry1
            = new AbstractMap.SimpleImmutableEntry<>(1, "one");
entry1.setValue("two");
System.out.println(entry1.getValue());

在这里插入图片描述
2、org.apache.commons.lang3.tuple 包中提供的Pair抽象类,它有两个子类,分别代表可变与不可变配对:ImmutablePair 和 MutablePair,用法等同于SimpleEntry 和 SimpleImmutableEntry
3、Collections.singletonMap()方法
无论是修改或是新增K,V,都会抛出UnsupportedOperationException异常

Map<String, Integer> mapPair = Collections.singletonMap("aaa", 3);

4、还有一些第三方组件,这里不一一例举,同样我们也可以根据自己的需要,实现我们自定义的Pair

class Pair<U, V> {
    public final U first;
    public final V second;
 
    private Pair(U first, V second) {
        this.first = first;
        this.second = second;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
 
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
 
        Pair<?, ?> pair = (Pair<?, ?>) o;
 
        if (!first.equals(pair.first)) {
            return false;
        }
        return second.equals(pair.second);
    }
 
    @Override
    public int hashCode() {
        return 31 * first.hashCode() + second.hashCode();
    }
 
    @Override
    public String toString() {
        return "(" + first + ", " + second + ")";
    }
 
    public static <U, V> Pair <U, V> of(U a, V b) {
        return new Pair<>(a, b);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr Yin

您获益,我得意,您打赏,我敬礼

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值