CharSequence源码分析
CharSequence是一个接口,表示一个char值的可读序列,此接口为多种char序列提供统一的、只读的通道。既然是接口,就不能通过new来进行赋值,只能通过以下方式赋值:
CharSequence cs = "ss";
该接口有4个常规方法和两个default方法(这两个暂时先不分析了)。
int length();
char charAt(int index);
CharSequence subSequence(int start, int end);
public String toString();
*
* @return an IntStream of char values from this sequence
* @since 1.8
*/
public default IntStream chars() {
class CharIterator implements PrimitiveIterator.OfInt {
int cur = 0;
public boolean hasNext() {
return cur < length();
}
public int nextInt() {
if (hasNext()) {
return charAt(cur++);
} else {
throw new NoSuchElementException();
}
}
@Override
public void forEachRemaining(IntConsumer block) {
for (; cur < length(); cur++) {
block.accept(charAt(cur));
}
}
}
return StreamSupport.intStream(() ->
Spliterators.spliterator(
new CharIterator(),
length(),
Spliterator.ORDERED),
Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,
false);
}
*
* @return an IntStream of Unicode code points from this sequence
* @since 1.8
*/
public default IntStream codePoints() {
class CodePointIterator implements PrimitiveIterator.OfInt {
int cur = 0;
@Override
public void forEachRemaining(IntConsumer block) {
final int length = length();
int i = cur;
try {
while (i < length) {
char c1 = charAt(i++);
if (!Character.isHighSurrogate(c1) || i >= length) {
block.accept(c1);
} else {
char c2 = charAt(i);
if (Character.isLowSurrogate(c2)) {
i++;
block.accept(Character.toCodePoint(c1, c2));
} else {
block.accept(c1);
}
}
}
} finally {
cur = i;
}
}
public boolean hasNext() {
return cur < length();
}
public int nextInt() {
final int length = length();
if (cur >= length) {
throw new NoSuchElementException();
}
char c1 = charAt(cur++);
if (Character.isHighSurrogate(c1) && cur < length) {
char c2 = charAt(cur);
if (Character.isLowSurrogate(c2)) {
cur++;
return Character.toCodePoint(c1, c2);
}
}
return c1;
}
}
return StreamSupport.intStream(() ->
Spliterators.spliteratorUnknownSize(
new CodePointIterator(),
Spliterator.ORDERED),
Spliterator.ORDERED,
false);
}
测试:
package com.test;
public class Test {
@org.junit.Test
public void test(){
CharSequence cs = "welcome";
System.out.println("字符序列的长度:"+cs.length());
System.out.println("截取第一位字符(原字符序列不改变):"+cs.subSequence(0, 2));
System.out.println("字符序列转换成字符串表示:"+cs.toString());
System.out.println("返回第一个字符:"+cs.charAt(6));
}
}
结果:
身体是革命的本钱,爱跑步,爱生活!