这个地方要注意,基本类型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);
}