以下學習根據JDK1.7String類源代碼做註釋
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { //String類是final的,也就是說String類不允許被繼承,實現了Serializable接口(可以序列化和反序列化),Comparale(可以進行自定義的字符串比較) CharSequence(一個可讀序列。此接口對許多不同種類的 char 序列提供統一的只讀訪問。StringBuilder 和StringBuffer也實現了這個接口)
private final char value[]; //用於存放string字符的數組 private int hash; //表示string字符的哈希值,默認爲0
//默認構造方法,一般不用,因爲String字符串是不可改變的 public String() { this.value = new char[0]; } //有參構造方法,使用已存在的一個字符串創建一個相同字符序列的字符串 public String(String original) { this.value = original.value; this.hash = original.hash; } //使用一個字符數組創建一個字符串 public String(char value[]) { this.value = Arrays.copyOf(value, value.length); //使用Arrays類複製字符數組並賦值給String類聲明的value } //使用字符數組的一部分創建一個字符串對象 offset字符數組開始位置,count數組開始位置往後的長度 public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.value = Arrays.copyOfRange(value, offset, offset+count); }
//將字節數組從offset開始,長度爲length並以chatsetName編碼轉換成字符串 public String(byte bytes[], int offset, int length, String charsetName) throws UnsupportedEncodingException { if (charsetName == null) throw new NullPointerException("charsetName"); checkBounds(bytes, offset, length); this.value = StringCoding.decode(charsetName, bytes, offset, length); }
//返回字符串的長度 public int length() { return value.length; } //判斷字符串長度是否爲0 public boolean isEmpty{ retutn value.length==0 } //根據下標獲取字符 public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; } //equals 比較的是值 public boolean equals(Object anObject) { if (this == anObject) {//如果是同一個對象,返回true return true; } if (anObject instanceof String) { //判斷是否是string對象 String anotherString = (String) anObject; int n = value.length; if (n == anotherString.value.length) {//判斷長度是否一致 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; }
//採用乘法hash算法,字符串相同hash值一定相同,hash值相同,不一定字符串相同 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值乘31+該字符 } hash = h; } return h; }