Appendable 是 Java 中的一个接口,主要用于向字符序列添加字符或字符序列。它提供了一些方法,使得实现类可以接收字符输入,并将这些字符添加到其内部存储中。该接口是为了处理字符的追加操作而设计的,常用于构建字符串、字符缓冲等场景。
主要方法:
Appendable append(char c) 将指定字符 c 追加到 Appendable 对象中。如果发生 IOException,则将其抛出。
Appendable append(CharSequence csq) 将指定的字符序列 csq 追加到 Appendable 对象中。如果发生 IOException,则将其抛出。
Appendable append(CharSequence csq, int start, int end) 将 csq 的子序列(从 start 开始,到 end - 1 结束)追加到 Appendable 对象中。如果发生 IOException,则将其抛出。
一些常见的实现了 Appendable 接口的类包括 StringBuilder、StringBuffer 和 PrintWriter 等。这些类通过实现 Appendable 接口的方法,可以方便地将字符或字符序列添加到自身的内部存储中。
利用 StringBuilder 实现字符串追加,代码如下:
import java.io.IOException;
public class AppendableExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
try {
// 使用 StringBuilder 实现 Appendable 接口
Appendable appendable = sb;
// 追加一个字符
appendable.append('H');
// 追加一个字符序列
appendable.append("ello");
// 追加一个字符序列的子序列
appendable.append(", World!", 0, 7);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sb.toString());
}
}简单创建一个实现了 Appendable 接口的类,用来验证接口用法,代码如下:
package com.hxstrive.java_lang;
import java.io.IOException;
/**
* Appendable 示例
* @author hxstrive
*/
public class AppendableExample2 {
public static void main(String[] args) {
MyAppendable sb = new MyAppendable();
try {
// 使用 StringBuilder 实现 Appendable 接口
Appendable appendable = sb;
// 追加一个字符
appendable.append('H');
// 追加一个字符序列
appendable.append("ello");
// 追加一个字符序列的子序列
appendable.append(", World!", 0, 7);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sb.toString()); // Hello, World
}
static class MyAppendable implements Appendable {
private static final ThreadLocal<String> local = new ThreadLocal<>();
public MyAppendable() {
local.set("");
}
@Override
public Appendable append(CharSequence csq) throws IOException {
local.set(local.get() + csq);
return this;
}
@Override
public Appendable append(CharSequence csq, int start, int end) throws IOException {
local.set(local.get() + csq.subSequence(start, end));
return this;
}
@Override
public Appendable append(char c) throws IOException {
local.set(local.get() + c);
return this;
}
@Override
public String toString() {
return local.get();
}
}
}