ByteBuffer之equals和compareTo比较

ByteBuffer介绍

ByteBuffer是Java NIO的重要组成部分。如何比较2个ByteBuffer是否相等可以使用equals()、compareTo()两个方法。

equals()

源码分析

public boolean equals(Object ob) {
    if (this == ob)
        return true;
    if (!(ob instanceof ByteBuffer))
        return false;
    ByteBuffer that = (ByteBuffer)ob;
    if (this.remaining() != that.remaining())
        return false;
    int p = this.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;
}

判断的逻辑是:
1、如果是自身,true。
2、如果不是ByteBuffer,false
3、remaining()是否一样,如果不一样,返回false。remaining = limit - position。
4、两个ByteBuffer的position~limit的数据是否一样,一样true,不一样返回false。
Buffer的重要指标:position、limit参与了比较。但是mark、capacity却没有参与比较。

测试

@Test
public void test1(){
    ByteBuffer b1 = ByteBuffer.wrap(new byte[]{1,2,3,4,5});
    ByteBuffer b2 = ByteBuffer.wrap(new byte[]{1,2,3,4,5,1,2,3,4,5});
    BufferUtil.print(b1);
    BufferUtil.print(b2);
    System.out.println(b1.equals(b2)); //false
    b2.position(5);
    BufferUtil.print(b2);
    System.out.println(b1.equals(b2)); //true
}

在这里插入图片描述

compareTo()

源码分析

public int compareTo(ByteBuffer that) {
    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));
        if (cmp != 0)
            return cmp;
    }
    return this.remaining() - that.remaining();
}

private static int compare(byte x, byte y) {
    return Byte.compare(x, y);
}

大概意思是:
1、从2个ByteBuffer的当前位置position开始比较每个字节,如果出结果了就return。
2、否则就比较2个ByteBuffer的剩余元素个数。

测试

@Test
public void test2(){
    ByteBuffer b1 = ByteBuffer.wrap(new byte[]{1,2,3,4,5});
    ByteBuffer b2 = ByteBuffer.wrap(new byte[]{0,1,2,3,4,5,6});
    b2.position(1);
    System.out.println(b1.compareTo(b2)); //-1

    b1.clear();
    b2.clear();
    System.out.println(b1.compareTo(b2)); //1
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值