参考:https://www.jianshu.com/p/cbec7786d8f1
https://www.jianshu.com/p/5c4f5feeb9d4
今天看别人代码时,偶尔发现,用来存在一组KEY_VALUE值时,代码使用的是 new Pair<String, Integer>(fileName, Version),刚开始还以为是写的bean呢,点了一下,才知道是自带的源码。好奇这到底是什么东东?是谁提供的呢?
1、Pair.create(fileName, updateVersion);
2、直接new
new Pair<String, Integer>(fileName, Version),
在某些情况下,既需要已键值的方式存储数据列表,还需要在输出的时候保持顺序。HashMap满足前者,ArrayList则满足后者,再不打算去多做修改且数据类型相对简单时,可以选择Android提供的一种工具类:Pair(搭配ArrayList)。
原来这是一个容器,使用效果,个人感觉:
- 1、利用Pair和既有数据组成 组元素,不破坏原有结构的同时让两个数据产生绑定关系。
- 2、利用Pair和List结合,形成类似Map的效果。
- 3、它的equal比较的是值
下面是源码
/**
* Container to ease passing around a tuple of two objects. This object provides a sensible
* implementation of equals(), returning true if equals() is true on each of the contained
* objects.
*/
public class Pair<F, S> {
public final F first;
public final S second;
/**
* Constructor for a Pair.
*
* @param first the first object in the Pair
* @param second the second object in the pair
*/
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
/**
* Checks the two objects for equality by delegating to their respective
* {@link Object#equals(Object)} methods.
*
* @param o the {@link Pair} to which this one is to be checked for equality
* @return true if the underlying objects of the Pair are both considered
* equal
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) {
return false;
}
Pair<?, ?> p = (Pair<?, ?>) o;
return Objects.equals(p.first, first) && Objects.equals(p.second, second);
}
/**
* Compute a hash code using the hash codes of the underlying objects
*
* @return a hashcode of the Pair
*/
@Override
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}
@Override
public String toString() {
return "Pair{" + String.valueOf(first) + " " + String.valueOf(second) + "}";
}
/**
* Convenience method for creating an appropriately typed pair.
* @param a the first object in the Pair
* @param b the second object in the pair
* @return a Pair that is templatized with the types of a and b
*/
public static <A, B> Pair <A, B> create(A a, B b) {
return new Pair<A, B>(a, b);
}
}