java中的Pair对

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cainiao111112/article/details/82893017

应用场景:

              当涉及到key-value键值对时,我们一般使用Map映射去做处理,此时的key相当于value的一个描述或者引用,而具体的信息都保存在value中,我们可以通过key去获取对应的value。但是当key和value都保存具体信息时,我们就需要用到Pair对了。

              实际上Pair保存的应该说是一个信息对,两个信息都是我们需要的,没有key和value之分。

具体的实现:

1.在javax.util包下,有一个简单Pair类。

/**
     * Key of this <code>Pair</code>.
     */
    private K key;

    /**
     * Gets the key for this pair.
     * @return key for this pair
     */
    public K getKey() { return key; }

    /**
     * Value of this this <code>Pair</code>.
     */
    private V value;

    /**
     * Gets the value for this pair.
     * @return value for this pair
     */
    public V getValue() { return value; }

    /**
     * Creates a new pair
     * @param key The key for this pair
     * @param value The value to use for this pair
     */
    public Pair(@NamedArg("key") K key, @NamedArg("value") V value) {
        this.key = key;
        this.value = value;
    }

用法:

Pair<String, String> pair = new Pair<>("aku", "female");
pair.getKey();
pair.getValue();

2.在Apache Commons库中,org.apache.commons.lang3.tuple 包中提供Pair抽象类,它有两个子类,分别代表可变与不可变配对:ImmutablePair 和 MutablePair。两者都实现了访问key/value以及setter和getter方法。

public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {

  
    /**
     * @return 返回一个不可变的Pair对ImmutablePair
     */
    public static <L, R> Pair<L, R> of(final L left, final R right) {
        return new ImmutablePair<>(left, right);
    }

   
    public abstract L getLeft();

    
    public abstract R getRight();

   
    @Override
    public final L getKey() {
        return getLeft();
    }

    
    @Override
    public R getValue() {
        return getRight();
    }


}

用法:

Pair<String, String> pair = Pair.of("aku", "female");
pair.getLeft();
pair.getRight();

猜你喜欢

转载自blog.csdn.net/Cainiao111112/article/details/82893017
今日推荐