a. String类
a. String类
更新日期:2020-07-23
1. 概览String类
目前我使用的版本为JDK11。从字符串类的定义中可以发现它引用了不少其它的类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | import java.io.ObjectStreamField;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Native;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
import java.util.Objects;
import java.util.Spliterator;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
|
从这里可以发现字符串和以下几件事情有关:
- Stream
- 本地化
- 编码
- 字符串分割
- 注解
- 字符串连接
- 字符
- 正则表达式
- 数组列表
- stream输入输出
- 比较函数
- 未知jdk.internal
- 格式化
通过查看java.lang.String的源码,我发现了几个事情:
- a. String默认使用UTF16编码,并且可以转换为其它编码。
- b. 可以忽略大小写进行比较。
- c. 可以指定比较字符串的某一段。(包括前缀比较和后缀比较。)
- d. 可以查找指定的字符或者小字符串在整个字符串的位置。
- e. 查找个替换都可以指定起始位置。替换可以替换第一个或者替换全部。
- f. 字符串去首尾的空格时可以指定只去开头或者只取结尾的空格。
- g. 可以判断字符串是否全部由空格组成。
- h. 可以将带行终止符的字符串转化为多行字符串。
- i. 可以重复字符串指定次数。(不知道哪里能用得上。)
2. 比较有用的几个处理
2.1 字符串连接
常见的用「,」连接字符串的操作就可以用这个函数来实现。再也不用头疼什么「,」多不多一个的问题了。
| public static String join(CharSequence delimiter, CharSequence... elements);
|
2.2 高速String处理类
2.2.1 StringBuffer
这个类最重要的方法是:append。此方法不仅仅可以接受字符串参数,更可以接受任何能够转换为字符串的类型。
这个类包括很多字符串的通用操作,这是String类所不具备的。比如:
String类中的内容是不能够更改的,这个看起来更像是数组或列表的操作。而且这些操作都返回StringBuffer,所以这些操作都可以串起来用。
能够读写Object的输入输出流:
2.2.2 StringBuilder
据查看源码,这个类中的方法与StringBuffer如出一辙。用法一模一样,那么这两个类有什么区别呢。
2.2.3 StringBuffer与StringBuilder
从年代看:
- StringBuffer 1994
- StringBuilder 2003
再看源码中的文档第一句描述。
StringBuffer:
| /**
* A thread-safe, mutable sequence of characters.
*/
|
StringBuilder:
| /**
* A mutable sequence of characters. This class provides an API compatible
* with {@code StringBuffer}, but with no guarantee of synchronization.
* This class is designed for use as a drop-in replacement for
* {@code StringBuffer} in places where the string buffer was being
* used by a single thread (as is generally the case). Where possible,
* it is recommended that this class be used in preference to
* {@code StringBuffer} as it will be faster under most implementations.
*/
|
说了半天,其实StringBuffer是一个线程安全的类。StringBuilder不线程安全。
也就是说在字符串只在单线程中使用时,应该使用StringBuilder,因为它比StringBuffer快。如果这个字符串被多个线程共用,则使用StringBuffer。
更多时候,字符串类只在局部使用,所以StringBuilder更加的常用。