Why Commons Lang Pair implements Map Entry?

487 views Asked by At
1

There are 1 answers

2
Quang Nguyen On

First let's have a look in to the class Pair at the overridden methods, it's nothing but delegations on the "native" getLeft() and getRight()

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

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

And now take a look at the static method of class ImmutablePair

/**
 * <p>Creates an immutable pair from an existing pair.</p>
 *
 * <p>This factory allows the pair to be created using inference to
 * obtain the generic types.</p>
 *
 * @param <L> the left element type
 * @param <R> the right element type
 * @param pair the existing pair.
 * @return a pair formed from the two parameters, not null
 * @since 3.10
 */
public static <L, R> ImmutablePair<L, R> of(final Map.Entry<L, R> pair) {
    final L left;
    final R right;
    if (pair != null) {
        left = pair.getKey();
        right = pair.getValue();
    } else {
        left = null;
        right = null;
    }
    return new ImmutablePair<>(left, right);
}

So no matter if you pass a type of the interface Map.Entry you will get a ImmutablePair back. The library can handle not only MutablePair, ImmutablePair but also what ever which is subtype of Map.Entry. Maybe it could be your custom implementation of Map.Entry.