java String

java String 源码

String 类底层是 char 类型数组实现的。

String 类API 文档描述如下:
String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例来实现。

字符串是常量;它们的值在创建之后不能改变。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享它们。例如:


   
String str = "abc";
等效于:
 
char data[] = {'a', 'b', 'c'};
String str = new String(data);


讨论 String的值为什么不可变:
String类被定义为 final ,且jdk的API中没有提供可以更改char[]值的方法。
至于substring 、replace 方法等均是重新生成一个新的String对象,而并不改变原先对象。

java语言 String中有字符串常量池的概念:

    
String s1 = "hello";
String s2 = "hello";


String类有一个特殊的创建方法,就是使用""双引号来创建
上述的代码创建String 实例步骤

1.查看常量池中是否存在内容为 hello 的相同字符串对象

2.若没有,就在常量池中创建一个包含该内容的字符串对象,并让引用变量指向该对象

3若已经存在,则让字符串引用直接指向常量池中对象

上例中 s1==s2 为true;

    
String s3 = new String("hello world");
String s4 = "hello world";


String s3 = new String("hello world")
实际创建了2个String对象,一个是"hello world"通过""双引号创建的,另一个是通过new创建的.只不过他们创建的时期不同,一个是编译期,一个是运行期!
这时 s3 == s4 为false;两个不同的对象。


再看 String 类定义:



public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
//底层维护的是char 数组。
private final char value[];

/** The offset is the first index of the storage that is used. */
private final int offset;

/** The count is the number of characters in the String. */
private final int count;

/** Cache the hash code for the string */
private int hash; // Default to 0



String 重写了equals方法:


   
public boolean equals(Object anObject) {
//比较地址
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
//比较两字符串char[]数组里的值。一一对应比较。
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值