CharBuffer equals()方法的工作原理是什么? [英] How exactly CharBuffer equals() method works?

查看:70
本文介绍了CharBuffer equals()方法的工作原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 CharBuffer equals()方法功能的具体细节.

I cannot understand particular details of CharBuffer equals() method functioning.

我不理解这个独立于他们的起始位置"的说法:

I don't understand this "considered independently of their starting positions" phrase:

当且仅当

它们具有相同的元素类型,

They have the same element type,

它们具有相同数量的剩余元素,并且

They have the same number of remaining elements, and

剩余元素的两个序列,独立于它们的起始位置是逐点相等的.

The two sequences of remaining elements, considered independently of their starting positions, are pointwise equal.

我研究了这些好例子-更多例子,但是我不明白这个主意.

I studies these good examples - more examples, but I don't understand the idea.

有人可以用最少的洞察力示例代码用不同的词来解释吗?

Could anyone explain in different words and with minimal insightful example code?

尤其是我觉得很奇怪:

CharBuffer cb1 = CharBuffer.allocate(10);
cb1.put('a');
cb1.put('b');
//cb1.rewind();
System.out.println(cb1);


CharBuffer cb2 = CharBuffer.allocate(10);
cb2.put(4,'a');
cb2.put(5,'b');
//cb2.rewind();
System.out.println(cb2);

// false, uncommenting rewind() - also false
// but shall be true - "considered independently of starting positions" ?
System.out.println(cb1.equals(cb2));  

推荐答案

CharBuffer 与它们的剩余内容进行比较.这意味着 equals()检查从当前缓冲区位置开始,而不是从缓冲区开始处开始.根据 Buffer.position() :

The CharBuffer are compared by what is their remaining content. It means that the equals() check starts from the current buffer position and not from the buffer start. As per Buffer.position():

缓冲区的位置是下一个要读取或写入的元素的索引.缓冲区的位置永远不会为负,也永远不会大于其限制.

A buffer's position is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit.

某些方法,例如 put(char)将更改缓冲区位置:

Some methods like put(char) will change the buffer position:

CharBuffer cb1 = CharBuffer.allocate(10);
cb1.put('a'); // increments position
cb1.put('b'); // increments position

CharBuffer cb2 = CharBuffer.allocate(8);

System.out.println(cb1.equals(cb2)); // true, 00000000 equals 00000000

在您的示例中,在 cb1.rewind()之后,第一个缓冲区是 ab00000000 ,而第二个缓冲区是 0000ab0000 .不需要调用 cb2.rewind(),因为 put(char,int)不会更改缓冲区位置:

In your example after cb1.rewind() the first buffer is ab00000000 while the second buffer is 0000ab0000. Calling cb2.rewind() is not needed as put(char, int) doesn't change the buffer position:

CharBuffer cb1 = CharBuffer.allocate(10);
cb1.put((char) 0);
cb1.put((char) 0);
cb1.put((char) 0);
cb1.put((char) 0);
cb1.put('a');
cb1.put('b');
// put(char) increments position so we need to rewind
cb1.rewind(); 

CharBuffer cb2 = CharBuffer.allocate(10);
cb2.put(4, 'a');
cb2.put(5, 'b');

System.out.println(cb1.equals(cb2)); // true, 0000ab0000 equals 0000ab0000

这篇关于CharBuffer equals()方法的工作原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆