源码版本:JDK_1.7.0_55
String的常用方法
public final class String //注意final
implements java.io.Serializable, Comparable<String>, CharSequence {
//保证只能初始化一次,用字符数组来存
private final char value[];
// 存储hashCode,默认为0
private int hash;
//判断是否相等
public boolean equals(Object anObject) {
if (this == anObject) { //同一对象
return true;
}
if (anObject instanceof String) { //若同为String类型
String anotherString = (String) anObject;
int n = value.length; //本字符串长度
if (n == anotherString.value.length) { //长度相同,比较每个字符(ASCII码)是否相同
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true; //相等返回
}
}
return false;
}
//比较String的大小,返回的是 "str1 - str2"
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2); //得到小的长度(可以比较的最大长度)
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) { //从0比较到lim-1
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2; //不相等返回
}
k++;
}
return len1 - len2; //若v[lim-1]以前都相等,则判断长度,长的值大
}
//获得hashCode,赋值给hash
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
//若之前没有计算过hashCode,且存在String,则生成一个hashCode
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i]; //计算方法,为了唯一性.
}
hash = h;
}
return h;
}
/*看了下"zero"生成hashCode过程:
0:122
1:3883
2:120487
3:3735208
hashCode:3735208
*/
//得到某一字符
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) { //是否越界
throw new StringIndexOutOfBoundsException(index);
}
return value[index]; //直接下标返回
}
//替换方法
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) { //遍历判断第一个oldChar的位置
break;
}
}
if (i < len) { //存在oldChar
char buf[] = new char[len]; //重新生成等长字符数组
for (int j = 0; j < i; j++) {
buf[j] = val[j]; //0至i-1的值保持不变
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
//找到存在oldChar位置的地方,在新字符数组处赋值为newChar;
i++;
}
return new String(buf, true); //实际上是重新生成了一个String
}
}
return this;
}
//去掉两端的空格
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) { //从前往后判断
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) { //后往前
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
//substring(st, len),里面是用了Arrays里面的copyOfRange方法
/*
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];
//native方法
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
*/
}
public native String intern();
...
}