NIO的equals和compareTo源码分析

这个地方要注意,基本类型buffer一共有七个,每一个都复写了equals和compareTo方法,此处看的是IntBuffer
两个Buffer“相等”的依据
整个的过程就是读过的都已废弃,不作比较,比较从”此”以后开始
equals源码

  public boolean equals(Object ob) {
        if (this == ob)
            return true;
            //不是int类型的buffer
        if (!(ob instanceof IntBuffer))
            return false;
        IntBuffer that = (IntBuffer)ob;
        //剩余数量不相等
        if (this.remaining() != that.remaining())
            return false;
        //获取指针位置
        int p = this.position();
        //position后面的元素都是相等的
        for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
            if (!equals(this.get(i), that.get(j)))
                return false;
        return true;
    }

比如下面的代码就是相等的

public class TestBuffer {

    public static void main(String[] args) {
        IntBuffer dst = IntBuffer.allocate(5);
        dst.put(1);
        dst.put(3);
        System.out.println(dst.remaining());
        IntBuffer dst1 = IntBuffer.allocate(6);
        dst1.put(2);
        dst1.put(2);
        dst1.put(2);
        System.out.println(dst1.remaining());
        System.out.println(dst.equals(dst1));
    }
}
运行结果
3
3
true

compareTo方法[过期作废,只比较position后面的]

public int compareTo(IntBuffer that) {
//当前位置+比较者之中剩余byte最小值
        int n = this.position() + Math.min(this.remaining(), that.remaining());
        for (int i = this.position(), j = that.position(); i < n; i++, j++) {
        //取得比较结果
            int cmp = compare(this.get(i), that.get(j));、
            //不为0直接返回,这一点就说明,如果两者position后面的元素谁先出现较大者,谁获胜
            if (cmp != 0)
                return cmp;
        }
        //发现position后面都相等,那就看谁剩余byte多了,我们要的是潜力股
        return this.remaining() - that.remaining();
    }

    private static int compare(int x, int y) {
        return Integer.compare(x, y);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值