Pair的使用

Pair类的基本使用
一,需要依赖的maven包:

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.12.0</version>
</dependency>
注:版本不是必需,根据自己的情况选择

二,基本使用

Pair<String,Integer> pair = Pair.of("zhangsan",12);
String s = pair.getKey();
int i = pair.getValue();
System.out.println(s+","+i);
String l = pair.getLeft();
int r = pair.getRight();
System.out.println(l+","+r);

返回结果:
zhangsan,12
zhangsan,12

三,源码解读

public abstract class Pair<L, R> implements Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
    private static final long serialVersionUID = 4954918890077093841L;
    public static final Pair<?, ?>[] EMPTY_ARRAY = new Pair.PairAdapter[0];

    public Pair() {
    }

    public static <L, R> Pair<L, R>[] emptyArray() {
        return (Pair[])EMPTY_ARRAY;
    }

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

    public static <L, R> Pair<L, R> of(Entry<L, R> pair) {
        return ImmutablePair.of(pair);
    }

    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 Entry)) {
            return false;
        } else {
            Entry<?, ?> other = (Entry)obj;
            return Objects.equals(this.getKey(), other.getKey()) && Objects.equals(this.getValue(), other.getValue());
        }
    }

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

    public abstract L getLeft();

    public abstract R getRight();

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

四,总结
以上是Pair的基本使用,感觉Pair还挺方便的,终于可以在方法中返回两个结果了,不需要多写一个方法了。但是,个人建议还是少用为好,因为在项目中,我们都是多人协同开发,肯定会有你调用我写的方法,或者我调用你写的方法,在调用的过程中,你给我返了一个我不需要的数据,还得我做一些处理,这样无论是在代码的冗余度,还是效率上都不是很友好。所以说还是一个方法返回一个值,尽量做到一个方法只干一件事。如果是自己写的一些小工具,自己用的那就无所谓这些了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值