JDK1.8源码阅读(二)Java.lang.String

本文详细介绍了Java中String类的内部实现,包括其属性、构造方法及常用API,如length(), equals(), substring()等,同时解析了hashCode()的计算原理及其优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String

String定义

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {}

String是一个用final声明的常量类,不能被任何类继承,而且一个String类一旦被创建,包括这个对象中的字符串序列是不可改变的,包括该类后续的所有方法都是不能修改该对象的,直至该对象被销毁。然后String实现了Serializable接口,这是一个序列化标志接口。还实现了Comparable接口,用于比较两个字符串的大小(根据顺序比较单个字符的ASCII码),最后实现了CharSequence接口,表示是一个有序字符集合。

 

String属性

private final char value[]; //被final修饰的char数组,用来存储字符串
private int hash;//默认是0,缓存字符串的哈希码
private static final long serialVersionUID = -6849794470754667710L;//序列化标识

String构造方法

String方法

1.public int length() { return value.length; }

返回一个整形,上面说了String类用char数组value保存字符串,这个数组的长度也就是字符串的长度。

2.public boolean isEmpty() { return value.length == 0; }

返回Boolean,判断字符串是否长度为0为空。

3.

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

根据下标,返回指定位置单个字符。

4.

public int codePointAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return Character.codePointAtImpl(value, index, value.length);
}

没用过,返回指定索引处的字符(Unicode 代码点)。

5.

public int codePointBefore(int index) {
    int i = index - 1;
    if ((i < 0) || (i >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return Character.codePointBeforeImpl(value, index, 0);
}

返回此String 中从给定的 index 处偏移 codePointOffset 个代码点的索引(不是很懂~)

6.

public int codePointCount(int beginIndex, int endIndex) {
    if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
        throw new IndexOutOfBoundsException();
    }
    return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
}

返回码点的长度

7.

public int offsetByCodePoints(int index, int codePointOffset) {
    if (index < 0 || index > value.length) {
        throw new IndexOutOfBoundsException();
    }
    return Character.offsetByCodePointsImpl(value, 0, value.length,
            index, codePointOffset);
}

返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。 

8.

void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, 0, dst, dstBegin, value.length);
}

获取字符串指定索引字符,装入数组返回。

9.public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {在Java中,String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组。

10.public boolean equals(Object anObject)

String类重写了equals方法,判断两个字符串的组成是否相同。

11.public boolean contentEquals(StringBuffer sb) { return contentEquals((CharSequence)sb); }

跟StringBuffer相比是否组成相同。

12.public boolean equalsIgnoreCase(String anotherString)

判断字符串长度是否相等。

13.public int compareTo(String anotherString)

比较字符串大小(ASCII码顺序),区分大小写

14.public int compareToIgnoreCase(String str)

比较字符串大小(ASCII码顺序),不区分大小写

15.public boolean regionMatches

用于检测两个字符串在一个区域内是否相等。

16.public boolean startsWith(String prefix, int toffset)

检测字符串是否以指定的前缀开始。

17.public boolean endsWith

检测字符串是否以指定的字符结束。

18.public int hashCode()

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

计算类的哈希值,s 数组即源码中的 val 数组,也就是构成字符串的字符数组。这里有个数字 31 ,为什么选择31作为乘积因子,而且没有用一个常量来声明?主要原因有两个:

  ①、31是一个不大不小的质数,是作为 hashCode 乘子的优选质数之一。

  ②、31可以被 JVM 优化,31 * i = (i << 5) - i。因为移位运算比乘法运行更快更省性能。

19.public int indexOf(int ch)//(int ch, int fromIndex)、(String str)、(String str, int fromIndex):

判断String对象有没有包含某字符

20.public int lastIndexOf

从后往前查String对象是否包含某字符。

21.public String substring(int beginIndex)、(int beginIndex, int endIndex)

substring(int beginIndex):返回一个从索引 beginIndex 开始一直到结尾的子字符串。

substring(int beginIndex, int endIndex)返回一个从索引 beginIndex 开始,到 endIndex 结尾的子字符串。

22.public CharSequence subSequence(int beginIndex, int endIndex)

方法返回一个新的字符序列,它是此序列的一个子序列。

23.public String concat(String str)

在字符串尾部添加传入参数,并返回一个新的String对象。

24.public String replace

replace(char oldChar, char newChar) :将原字符串中所有的oldChar字符都替换成newChar字符,返回一个新的字符串。

25.String replaceAll(String regex, String replacement):将匹配正则表达式regex的匹配项都替换成replacement字符串,返回一个新的字符串。

26.public boolean matches(String regex)

用于检测字符串是否匹配给定的正则表达式。

27.public boolean contains

判断字符串str中是否有子字符串。如果有则返回true,如果没有则返回false。

28.public String replaceFirst(String regex, String replacement)

根据正则表达式替换字符串。

29.public String[] split(String regex, int limit)

在给定的正则表达式来分割该字符串.此方法返回的数组包含此字符串的子字符串,每个子字符串都由另一个匹配给定表达式的子字符串终止,或者由此字符串末尾终止。数组中的子字符串按它们在此字符串中出现的顺序排列。如果表达式不匹配输入的任何部分,那么所得数组只具有一个元素,即此字符串。

 

30.public static String join

将数组或集合以某拼接符拼接到一起形成新的字符串。

31.public String toLowerCase

转小写

32.public String toUpperCase

转大写

33.public String trim()

去除两端留白。

34.public char[] toCharArray()

将字符串返回成char数组

35.public static String format

字符串格式化

36.public static String valueOf(char data[])

由基本数据型态转换成String

(1)String.valueOf(boolean b) : 将 boolean 变量 b 转换成字符串 

(2)String.valueOf(char c) : 将 char 变量 c 转换成字符串 
(3)String.valueOf(char[] data) : 将 char 数组 data 转换成字符串 
(4)String.valueOf(char[] data, int offset, int count) : 将 char 数组 data 中 由 data[offset] 开始取 count 个元素 转换成字符串 

(5)String.valueOf(double d) : 将 double 变量 d 转换成字符串 
(6)String.valueOf(float f) : 将 float 变量 f 转换成字符串 
(7)String.valueOf(int i) : 将 int 变量 i 转换成字符串 
(8)String.valueOf(long l) : 将 long 变量 l 转换成字符串 
(9)String.valueOf(Object obj) : 将 obj 对象转换成 字符串, 等于 obj.toString() 

由 String 转换成 数字的基本数据型态 

  要将 String 转换成基本数据型态转 ,大多需要使用基本数据型态的包装类别 

  比如说 String 转换成 byte ,可以使用 Byte.parseByte(String s) ,这一类的方法如果无法将 s 分析 则会丢出 NumberFormatException 

(1)byte : Byte.parseByte(String s) : 将 s 转换成 byte 

(2)Byte.parseByte(String s, int radix) : 以 radix 为基底 将 s 转换为 byte ,比如说 Byte.parseByte("11", 16) 会得到 17 

(3)double : Double.parseDouble(String s) : 将 s 转换成 double 

(4)float : Double.parseFloat(String s) : 将 s 转换成 float 

(5)int : Integer.parseInt(String s) : 将 s 转换成 int 

(6)long : Long.parseLong(String s)

37.这个方法是一个 native 的方法,但注释写的非常明了。“如果常量池中存在当前字符串, 就会直接返回当前字符串. 如果常量池中没有此字符串, 会将此字符串放入常量池中后, 再返回”。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值