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