Java : Appendable - API使用例
Appendable (Java SE 21 & JDK 21) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様書のおともにどうぞ。
概要
Appendableは、文字(char) と文字シーケンス(CharSequence) を追加するためのインタフェースです。
try (final var writer = new StringWriter()) {
final Appendable appendable = writer;
appendable.append("abc").append('-').append("XYZ");
System.out.println(writer); // abc-XYZ
}
final var cb = CharBuffer.allocate(7);
final Appendable appendable = cb;
appendable.append("abc").append('-').append("XYZ");
System.out.println(Arrays.toString(cb.array())); // [a, b, c, -, X, Y, Z]
メソッド
Appendable append (char c)
final var cb = CharBuffer.allocate(3);
final Appendable appendable = cb;
appendable.append('a').append('b').append('c');
System.out.println(Arrays.toString(cb.array())); // [a, b, c]
Appendable append (CharSequence csq)
final var cb = CharBuffer.allocate(6);
final Appendable appendable = cb;
appendable.append("abc").append("XYZ");
System.out.println(Arrays.toString(cb.array())); // [a, b, c, X, Y, Z]
final var cb = CharBuffer.allocate(7);
final Appendable appendable = cb;
final var sb = new StringBuilder();
sb.append("ab");
appendable.append(sb);
sb.append(123);
appendable.append(sb);
System.out.println(Arrays.toString(cb.array())); // [a, b, a, b, 1, 2, 3]
Appendable append (CharSequence csq, int start, int end)
final var cb = CharBuffer.allocate(6);
final Appendable appendable = cb;
final var csq = "abc";
appendable.append(csq, 0, 1);
System.out.println(Arrays.toString(cb.array())); // [a, , , , , ]
appendable.append(csq, 0, 2);
System.out.println(Arrays.toString(cb.array())); // [a, a, b, , , ]
appendable.append(csq, 0, 3);
System.out.println(Arrays.toString(cb.array())); // [a, a, b, a, b, c]
final var cb = CharBuffer.allocate(6);
final Appendable appendable = cb;
final var csq = "abc";
appendable.append(csq, 0, 3);
System.out.println(Arrays.toString(cb.array())); // [a, b, c, , , ]
appendable.append(csq, 1, 3);
System.out.println(Arrays.toString(cb.array())); // [a, b, c, b, c, ]
appendable.append(csq, 2, 3);
System.out.println(Arrays.toString(cb.array())); // [a, b, c, b, c, c]