我无法理解CharBuffer
equals()
方法功能的具体细节。
我不明白这个“独立于他们的起始位置”的说法:
当且仅当,
时,两个字符缓冲区相等它们具有相同的元素类型,
它们具有相同数量的剩余元素,并且
剩余元素的两个序列,独立于 它们的起始位置是逐点相等的。
我研究了这些好例子-more examples,但我不理解这个主意。
有人能用最少的洞察力示例代码用不同的词来解释吗?
我特别觉得这很奇怪:
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));
答案 0 :(得分:3)
剩余元素的两个顺序与它们的起始位置无关,按点相等。
在您的示例中,重要的是逐点相等部分:
./gradlew runIntegrationTests
// execution of dependent task
> Task :startWebappNodes
> Task :integrationTest
// .. test executing...
> Task :runIntegrationTests
Integration tests running finished
如您所见,按点比较char缓冲区的元素时,它们不匹配。
答案 1 :(得分:2)
将CharBuffer
的剩余内容进行比较。这意味着equals()
检查从当前缓冲区位置开始,而不是从缓冲区开始。根据{{3}}:
缓冲区的位置是下一个要读取或写入的元素的索引。缓冲区的位置永远不会为负,也永远不会超过其限制。
诸如put(char)
之类的某些方法将更改缓冲区位置:
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)
不会更改缓冲区位置:
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
答案 2 :(得分:0)
下面是一个示例,它为两个大小不同的缓冲区返回true
:
CharBuffer cb1 = CharBuffer.allocate(8);
cb1.put('x'); // moves the current position to 1
cb1.put('x'); // moves the current position to 2
cb1.put(2,'a');
cb1.put(3,'b');
System.out.print(cb1);System.out.println ('|');
CharBuffer cb2 = CharBuffer.allocate(10);
cb2.get (); // moves the current position to 1
cb2.get (); // moves the current position to 2
cb2.get (); // moves the current position to 3
cb2.get (); // moves the current position to 4
cb2.put(4,'a');
cb2.put(5,'b');
System.out.print(cb2);System.out.println ('|');
System.out.println(cb1.equals(cb2));
equals
将cb1
的位置2到7的元素与cb2
的位置4到9的元素进行比较,发现它们成对相等(两者都包含之后char
-'a','b',0,0,0,0)。
您可以看到两个缓冲区的起始位置不同(2对4),但是其余元素的顺序相同。
0 1 2 3 4 5 6 7 8 9
cb1 'x' 'x' 'a' 'b' 0 0 0 0
^
cb2 0 0 0 0 'a' 'b' 0 0 0 0
^
从起始位置开始比较序列时,会得到两个相同的序列。
在您的示例中,您正在将序列0,0,0,0,0,0,0,0(剩余元素的序列从位置2开始)与序列0,0,0,0,' a','b',0,0,0,0(其余元素的序列从位置0开始)。显然,它们彼此不相等。