• Java中的char、Character和CharSequence的区别


    char 与 Character

    char是一种基本的数据类型,Character是char类型的包装类,即通过Character创建出来的是一种对象。 

    Character是char的包装类,就像Integer和int,以及Long和long一样。

    包装类和基本类型可以自动转换,这是jdk1.5(5.0)的新特性,叫做自动封箱和自动解封

    自动拆箱、自动装箱

    1. char ch='a';
    2. Character ch1=ch;//自动封箱
    3. Character c=new Character(a);
    4. char c1=c;//自动解封

    如何理解Java中的自动拆箱和自动装箱? 

    定义:基本数据类型包装类之间可以自动地相互转换

    理解:装箱就是自动将基本数据类型转换为封装类型,拆箱就是自动将封装类型转换为基本数据类型。

    1. // 自动装箱
    2. 1. Integer a = 100;
    3. // 自动拆箱
    4. 2. int b = a;

    自动装箱,相当于Java编译器替我们执行了 Integer.valueOf(XXX);

    自动拆箱,相当于Java编译器替我们执行了 Integer.intValue(XXX);

    CharSequence

    CharSequence是一个描述字符串结构的接口,在这个接口里面一般发现有三种常用的子类:

    • 获取指定索引的字符:public char charAt​(int index) 
    • 获取字符串长度:public int length​()
    • 截取部分字符串:public CharSequence subSequence​(int start, int end)

    截取部分字符串代码样例

    1. public static void main(String[] args) {
    2. CharSequence str = "hello world";
    3. CharSequence sub = str.subSequence(6,11);
    4. System.out.println(sub);
    5. }

    CharSequence接口源码

    1. package java.lang;
    2. import java.util.NoSuchElementException;
    3. import java.util.PrimitiveIterator;
    4. import java.util.Spliterator;
    5. import java.util.Spliterators;
    6. import java.util.function.IntConsumer;
    7. import java.util.stream.IntStream;
    8. import java.util.stream.StreamSupport;
    9. /**
    10. * A CharSequence is a readable sequence of char values. This
    11. * interface provides uniform, read-only access to many different kinds of
    12. * char sequences.
    13. * A char value represents a character in the Basic
    14. * Multilingual Plane (BMP) or a surrogate. Refer to
    15. * href="Character.html#unicode">Unicode Character Representation for details.
    16. *
    17. *

      This interface does not refine the general contracts of the {@link

    18. * java.lang.Object#equals(java.lang.Object) equals} and {@link
    19. * java.lang.Object#hashCode() hashCode} methods. The result of comparing two
    20. * objects that implement CharSequence is therefore, in general,
    21. * undefined. Each object may be implemented by a different class, and there
    22. * is no guarantee that each class will be capable of testing its instances
    23. * for equality with those of the other. It is therefore inappropriate to use
    24. * arbitrary CharSequence instances as elements in a set or as keys in
    25. * a map.

    26. *
    27. * @author Mike McCloskey
    28. * @since 1.4
    29. * @spec JSR-51
    30. */
    31. public interface CharSequence {
    32. /**
    33. * Returns the length of this character sequence. The length is the number
    34. * of 16-bit chars in the sequence.
    35. *
    36. * @return the number of chars in this sequence
    37. */
    38. int length();
    39. /**
    40. * Returns the char value at the specified index. An index ranges from zero
    41. * to length() - 1. The first char value of the sequence is at
    42. * index zero, the next at index one, and so on, as for array
    43. * indexing.
    44. *
    45. *

      If the char value specified by the index is a

    46. * value is returned.
    47. *
    48. * @param index the index of the char value to be returned
    49. *
    50. * @return the specified char value
    51. *
    52. * @throws IndexOutOfBoundsException
    53. * if the index argument is negative or not less than
    54. * length()
    55. */
    56. char charAt(int index);
    57. /**
    58. * Returns a CharSequence that is a subsequence of this sequence.
    59. * The subsequence starts with the char value at the specified index and
    60. * ends with the char value at index end - 1. The length
    61. * (in chars) of the
    62. * returned sequence is end - start, so if start == end
    63. * then an empty sequence is returned.
    64. *
    65. * @param start the start index, inclusive
    66. * @param end the end index, exclusive
    67. *
    68. * @return the specified subsequence
    69. *
    70. * @throws IndexOutOfBoundsException
    71. * if start or end are negative,
    72. * if end is greater than length(),
    73. * or if start is greater than end
    74. */
    75. CharSequence subSequence(int start, int end);
    76. /**
    77. * Returns a string containing the characters in this sequence in the same
    78. * order as this sequence. The length of the string will be the length of
    79. * this sequence.
    80. *
    81. * @return a string consisting of exactly this sequence of characters
    82. */
    83. public String toString();
    84. /**
    85. * Returns a stream of {@code int} zero-extending the {@code char} values
    86. * from this sequence. Any char which maps to a
    87. * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code
    88. * point is passed through uninterpreted.
    89. *
    90. *

      If the sequence is mutated while the stream is being read, the

    91. * result is undefined.
    92. *
    93. * @return an IntStream of char values from this sequence
    94. * @since 1.8
    95. */
    96. public default IntStream chars() {
    97. class CharIterator implements PrimitiveIterator.OfInt {
    98. int cur = 0;
    99. public boolean hasNext() {
    100. return cur < length();
    101. }
    102. public int nextInt() {
    103. if (hasNext()) {
    104. return charAt(cur++);
    105. } else {
    106. throw new NoSuchElementException();
    107. }
    108. }
    109. @Override
    110. public void forEachRemaining(IntConsumer block) {
    111. for (; cur < length(); cur++) {
    112. block.accept(charAt(cur));
    113. }
    114. }
    115. }
    116. return StreamSupport.intStream(() ->
    117. Spliterators.spliterator(
    118. new CharIterator(),
    119. length(),
    120. Spliterator.ORDERED),
    121. Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,
    122. false);
    123. }
    124. /**
    125. * Returns a stream of code point values from this sequence. Any surrogate
    126. * pairs encountered in the sequence are combined as if by {@linkplain
    127. * Character#toCodePoint Character.toCodePoint} and the result is passed
    128. * to the stream. Any other code units, including ordinary BMP characters,
    129. * unpaired surrogates, and undefined code units, are zero-extended to
    130. * {@code int} values which are then passed to the stream.
    131. *
    132. *

      If the sequence is mutated while the stream is being read, the result

    133. * is undefined.
    134. *
    135. * @return an IntStream of Unicode code points from this sequence
    136. * @since 1.8
    137. */
    138. public default IntStream codePoints() {
    139. class CodePointIterator implements PrimitiveIterator.OfInt {
    140. int cur = 0;
    141. @Override
    142. public void forEachRemaining(IntConsumer block) {
    143. final int length = length();
    144. int i = cur;
    145. try {
    146. while (i < length) {
    147. char c1 = charAt(i++);
    148. if (!Character.isHighSurrogate(c1) || i >= length) {
    149. block.accept(c1);
    150. } else {
    151. char c2 = charAt(i);
    152. if (Character.isLowSurrogate(c2)) {
    153. i++;
    154. block.accept(Character.toCodePoint(c1, c2));
    155. } else {
    156. block.accept(c1);
    157. }
    158. }
    159. }
    160. } finally {
    161. cur = i;
    162. }
    163. }
    164. public boolean hasNext() {
    165. return cur < length();
    166. }
    167. public int nextInt() {
    168. final int length = length();
    169. if (cur >= length) {
    170. throw new NoSuchElementException();
    171. }
    172. char c1 = charAt(cur++);
    173. if (Character.isHighSurrogate(c1) && cur < length) {
    174. char c2 = charAt(cur);
    175. if (Character.isLowSurrogate(c2)) {
    176. cur++;
    177. return Character.toCodePoint(c1, c2);
    178. }
    179. }
    180. return c1;
    181. }
    182. }
    183. return StreamSupport.intStream(() ->
    184. Spliterators.spliteratorUnknownSize(
    185. new CodePointIterator(),
    186. Spliterator.ORDERED),
    187. Spliterator.ORDERED,
    188. false);
    189. }
    190. }
  • 相关阅读:
    第二章、dubbo 框架(直连方式 dubbo)
    一文详解Docker数据卷(volume)
    易语言 5.93静态编译报错
    ECCV 2022 | 视频插帧中的实时中间流估计
    Python爬虫实战第三例【三】(下)
    最优控制理论 九、Bellman动态规划法用于最优控制
    C现代方法(第17章)笔记——指针的高级应用
    解决了个bug,想说点啥但又难以启齿
    Django中重写model_to_dict方法,兼容接口返回展示时间和外键的
    CSS3 background-clip背景裁剪、CSS3 background-origin背景图片起点
  • 原文地址:https://blog.csdn.net/weixin_43715214/article/details/127997941