Android Pair记录

Pair

Pair位于android.util包,根据字面意思一对也可以判断出该对象可以存放一对值,的确被猜中了,其有first和second两个成员。

使用

该类使用比较简单,测试代码如下

Pair pair = new Pair(1, 2);
Pair pair2 = Pair.create("1", 2);
Pair pair3 = new Pair(1,2);
Log.i(TAG, pair.first.toString());
Log.i(TAG, pair.second.toString());
Log.i(TAG, pair.equals("1") + "");
Log.i(TAG, pair.equals(1) + "");
Log.i(TAG, pair2.first.equals("1") + "");
Log.i(TAG, pair2.first.equals(1) + "");
Log.i(TAG, pair.equals(1) + "");
Log.i(TAG, pair.equals(pair2) + "");
Log.i(TAG, pair.equals(pair) + "");
Log.i(TAG, pair.equals(pair3) + "");

测试log

07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: 1
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: 2
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: false
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: false
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: true
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: false
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: false
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: false
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: true
07-31 22:30:53.198 1351-1351/com.nan.lockscreen.test I/nan: true

源码

public class Pair<F, S> {
    //两成成员
    public final F first;
    public final S second;
    //构造方法赋值
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }
    //通过equals来比较两个Pair的相应位置的值,都为true则返回true
    @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);
    }
    //create实际还是通过构造方法直接对first和second成员进行赋值
    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}

V4下的Pair

使用和上述Pair完全相同,其中equals方法虽然实现不是通过Object下的equals方法实现,但实现逻辑与其完全相同

 public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return objectsEqual(p.first, first) && objectsEqual(p.second, second);
    }

private static boolean objectsEqual(Object a, Object b) {
    return a == b || (a != null && a.equals(b));
}

使用ArrayList的有序功能和HashMap的键值对功能时,可以采取ArrayList和Pair搭配使用

Map<Integer,Object> map=new HashMap<>();
List<Object> list=new ArrayList<>();
//配合使用
List<Pair<Integer,String>> sortList = new ArrayList<Pair<Integer, String>>();

猜你喜欢

转载自blog.csdn.net/w1070216393/article/details/76473547