public final class String implements java.io.Serializable, Comparable<String>, CharSequence
String類實現了Serializable能夠被序列化java
String類實現了Comparable能夠進行比較正則表達式
String類實現了CharSequence能夠按下標進行相關操做數組
而且String類使用final進行修飾,不能夠被繼承源碼分析
//用來存儲字符串的每個字符 private final char value[]; //hash值 private int hash; // Default to 0 //序列化版本號 private static final long serialVersionUID = -6849794470754667710L; //從變量名大體能夠看出和序列化有關,具體的不明白 private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];
//無參,直接使用空字符串賦值,hash爲0 public String() { this.value = "".value; } //使用已有字符串初始化 public String(String original) { this.value = original.value; this.hash = original.hash; } //使用char數組初始化,hash爲0 public String(char value[]) { this.value = Arrays.copyOf(value, value.length); } //使用字符數組,並指定偏移、字符個數初始化 public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count <= 0) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset <= value.length) { this.value = "".value; return; } } // 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); } //使用unicode編碼數組並指定偏移和數量進行初始化 public String(int[] codePoints, int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count <= 0) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset <= codePoints.length) { this.value = "".value; return; } } // Note: offset or count might be near -1>>>1. if (offset > codePoints.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } final int end = offset + count; // Pass 1: Compute precise size of char[] 計算char數組大小 int n = count; for (int i = offset; i < end; i++) { int c = codePoints[i]; if (Character.isBmpCodePoint(c))//判斷編碼是否是BMP(Basic Mutilingual Plane) continue; else if (Character.isValidCodePoint(c))//驗證編碼是否在unicode編碼範圍內 n++; else throw new IllegalArgumentException(Integer.toString(c)); } // Pass 2: Allocate and fill in char[] 申明char數組並填入編碼對應char final char[] v = new char[n]; for (int i = offset, j = 0; i < end; i++, j++) { int c = codePoints[i]; if (Character.isBmpCodePoint(c))//若是編碼是BMP直接一個字符就是接受 v[j] = (char)c; else Character.toSurrogates(c, v, j++);//轉換成兩個字符存儲 } this.value = v; } //使用ascii碼數組進行初始化 @Deprecated public String(byte ascii[], int hibyte, int offset, int count) { checkBounds(ascii, offset, count); char value[] = new char[count]; if (hibyte == 0) { for (int i = count; i-- > 0;) { value[i] = (char)(ascii[i + offset] & 0xff); } } else { hibyte <<= 8; for (int i = count; i-- > 0;) { value[i] = (char)(hibyte | (ascii[i + offset] & 0xff)); } } this.value = value; } @Deprecated public String(byte ascii[], int hibyte) { this(ascii, hibyte, 0, ascii.length); } //使用字節數組+字符集名初始化 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 String(byte bytes[], int offset, int length, Charset charset) { if (charset == null) throw new NullPointerException("charset"); checkBounds(bytes, offset, length); this.value = StringCoding.decode(charset, bytes, offset, length); } //使用字節數組+字符集名初始化 public String(byte bytes[], String charsetName) throws UnsupportedEncodingException { this(bytes, 0, bytes.length, charsetName); } //使用字節數組+字符集名初始化 public String(byte bytes[], Charset charset) { this(bytes, 0, bytes.length, charset); } //使用字節數組初始化 public String(byte bytes[], int offset, int length) { checkBounds(bytes, offset, length); this.value = StringCoding.decode(bytes, offset, length); } public String(byte bytes[]) { this(bytes, 0, bytes.length); } //使用StringBuffer初始化 public String(StringBuffer buffer) { synchronized(buffer) { this.value = Arrays.copyOf(buffer.getValue(), buffer.length()); } } //使用StringBuilder初始化 public String(StringBuilder builder) { this.value = Arrays.copyOf(builder.getValue(), builder.length()); }
public static String join(CharSequence delimiter, CharSequence... elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); // Number of elements not likely worth Arrays.stream overhead. StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); }
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); }
public static String format(String format, Object... args) { return new Formatter().format(format, args).toString(); }
public static String format(Locale l, String format, Object... args) { return new Formatter(l).format(format, args).toString(); }
public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
public static String valueOf(char data[]) { return new String(data); }
public static String valueOf(boolean b) { return b ? "true" : "false"; } public static String valueOf(char c) { char data[] = {c}; return new String(data, true); } public static String valueOf(int i) { return Integer.toString(i); } public static String valueOf(long l) { return Long.toString(l); } public static String valueOf(float f) { return Float.toString(f); } public static String valueOf(double d) { return Double.toString(d); }
public static String valueOf(char data[], int offset, int count) { return new String(data, offset, count); }
public static String copyValueOf(char data[], int offset, int count) { return new String(data, offset, count); }
public static String copyValueOf(char data[]) { return new String(data); }
public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { if (srcBegin < 0) { throw new StringIndexOutOfBoundsException(srcBegin); } if (srcEnd > value.length) { throw new StringIndexOutOfBoundsException(srcEnd); } if (srcBegin > srcEnd) { throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); } //System.arraycopy(Object src, int srcPos,Object dest, int destPos,int length) //src:要拷貝的源數組 //srcPos:源數組拷貝的起始位置 //dest:目標數組 //destPost:拷貝到目標數組的起始位置 //length:要拷貝元素的個數 System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); }
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException { if (charsetName == null) throw new NullPointerException(); return StringCoding.encode(charsetName, value, 0, value.length); }
public boolean equals(Object anObject) { if (this == anObject) {//地址相等兩對象equals爲true return true; } if (anObject instanceof 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])//有一個字符不相等最直接爲false return false; i++; } return true; } } return false; }
public boolean contentEquals(CharSequence cs) { // Argument is a StringBuffer, StringBuilder if (cs instanceof AbstractStringBuilder) { if (cs instanceof StringBuffer) { synchronized(cs) {//若是是StringBuffer那麼進行上鎖操做 return nonSyncContentEquals((AbstractStringBuilder)cs); } } else {//StringBuilder不上鎖 return nonSyncContentEquals((AbstractStringBuilder)cs); } } // Argument is a String if (cs instanceof String) { return equals(cs); } // Argument is a generic CharSequence char v1[] = value; int n = v1.length; if (n != cs.length()) { return false; } for (int i = 0; i < n; i++) {//其餘字符序列,一個一個字符進行比較 if (v1[i] != cs.charAt(i)) { return false; } } return true; }
public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null)//不爲空 && (anotherString.value.length == value.length)//字符個數相等 && regionMatches(true, 0, anotherString, 0, value.length);//忽略大小寫比較 } public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) { char ta[] = value; int to = toffset; char pa[] = other.value; int po = ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)value.length - len) || (ooffset > (long)other.value.length - len)) { return false; } while (len-- > 0) { char c1 = ta[to++]; char c2 = pa[po++]; if (c1 == c2) { continue; } if (ignoreCase) { // If characters don't match but case may be ignored, // try converting both characters to uppercase. // If the results match, then the comparison scan should // continue. //把兩個字符轉換成大寫的 char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) { continue; } // Unfortunately, conversion to uppercase does not work properly // for the Georgian alphabet, which has strange rules about case // conversion. So we need to make one last check before // exiting. //轉換成大寫的不相等,在轉換成小寫的判斷 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { continue; } } return false; } return true; }
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) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) {//若是當前字符串的字符比參數的大返回正數,不然返回負數 return c1 - c2; } k++; } //若是兩個字符串,長度小的字符串與長度大的前部分每一個字符都相等,若是兩字符串長度相等返回0,當前字符串長度大於參數字符串返回整數,當前字符串長度小於參數字符串返回負數 return len1 - len2; }
public int compareToIgnoreCase(String str) { return CASE_INSENSITIVE_ORDER.compare(this, str); } public int compare(String s1, String s2) { int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { //若是兩字符不相等,最後是轉換成小寫的進行比較 return c1 - c2; } } } } return n1 - n2; }
public boolean startsWith(String prefix) { return startsWith(prefix, 0); } public boolean startsWith(String prefix, int toffset) { char ta[] = value; int to = toffset; char pa[] = prefix.value; int po = 0; int pc = prefix.value.length; // Note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > value.length - pc)) { return false; } while (--pc >= 0) {//循環給定前綴字符串長度 if (ta[to++] != pa[po++]) {//前綴字符串字符和當前字符串字符比較 return false; } } return true; }
public boolean endsWith(String suffix) { return startsWith(suffix, value.length - suffix.value.length); }
public int hashCode() { //默認字符串hash爲0,若是是用另外一個字符串就等於另外一個字符串的hash int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) {//一個一個字符的變量 //前面字符的hash*31+當前字符的ascii碼 h = 31 * h + val[i]; } hash = h; } return h; }
public int indexOf(int ch) { return indexOf(ch, 0); } public int indexOf(int ch, int fromIndex) { final int max = value.length; if (fromIndex < 0) { fromIndex = 0; } else if (fromIndex >= max) {//若是查找的起始位置超過了數組下標 // Note: fromIndex might be near -1>>>1. return -1; } if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { //編碼是一個基本多語言編碼 // handle most cases here (ch is a BMP code point or a // negative value (invalid code point)) final char[] value = this.value; for (int i = fromIndex; i < max; i++) { if (value[i] == ch) { return i; } } return -1; } else { //獲取須要使用兩個char存儲的編碼的下標 return indexOfSupplementary(ch, fromIndex); } } private int indexOfSupplementary(int ch, int fromIndex) { if (Character.isValidCodePoint(ch)) {//是一個合法的unicode編碼 final char[] value = this.value; final char hi = Character.highSurrogate(ch); final char lo = Character.lowSurrogate(ch); final int max = value.length - 1; for (int i = fromIndex; i < max; i++) { if (value[i] == hi && value[i + 1] == lo) { return i; } } } return -1; }
public int lastIndexOf(int ch) { return lastIndexOf(ch, value.length - 1); } public int lastIndexOf(int ch, int fromIndex) { if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {//編碼是一個基本多語言unicode編碼,使用一個char存儲 // handle most cases here (ch is a BMP code point or a // negative value (invalid code point)) final char[] value = this.value; int i = Math.min(fromIndex, value.length - 1); for (; i >= 0; i--) { if (value[i] == ch) { return i; } } return -1; } else { //編碼使用兩個char存儲 return lastIndexOfSupplementary(ch, fromIndex); } } private int lastIndexOfSupplementary(int ch, int fromIndex) { if (Character.isValidCodePoint(ch)) { final char[] value = this.value; char hi = Character.highSurrogate(ch); char lo = Character.lowSurrogate(ch); int i = Math.min(fromIndex, value.length - 2); for (; i >= 0; i--) { if (value[i] == hi && value[i + 1] == lo) { return i; } } } return -1; }
public int indexOf(String str) { return indexOf(str, 0); } public int indexOf(String str, int fromIndex) { return indexOf(value, 0, value.length, str.value, 0, str.value.length, fromIndex); } static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } if (fromIndex < 0) { fromIndex = 0; } if (targetCount == 0) { return fromIndex; } char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; //計算終止下標 int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } } } return -1; }
public String substring(int beginIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } //計算長度 int subLen = value.length - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); }
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } //計算字符個數 int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }
public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } //獲取拼接字符串的長度 int len = value.length; //把原字符串的字符拷貝到一個大小爲原字符串大小+參數字符串大小的新數組中 char buf[] = Arrays.copyOf(value, len + otherLen); //把拼接字符串的字符拷貝到數組中 str.getChars(buf, len); return new String(buf, true); }
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) {//找到須要替換字符的位置 break; } } if (i < len) { char buf[] = new char[len]; for (int j = 0; j < i; j++) { buf[j] = val[j]; } while (i < len) { char c = val[i]; buf[i] = (c == oldChar) ? newChar : c;//把原字符替換爲新字符 i++; } return new String(buf, true); } } return this; }
public boolean matches(String regex) { return Pattern.matches(regex, this); }
public boolean contains(CharSequence s) { return indexOf(s.toString()) > -1; }
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; }
public char[] toCharArray() { // Cannot use Arrays.copyOf because of class initialization order issues char result[] = new char[value.length]; //使用System.arraycopy方法拷貝 System.arraycopy(value, 0, result, 0, value.length); return result; }
@Test public void test8() { String s1="abc"; String s2=new String("abc"); System.out.println(s1==s2);//false System.out.println(s1==s2.intern());//true }
使用s1="abc"這種方式棧中變量s1直接指向字符串常量池中的常量「abc」,而s2=new String("abc")這種方式,棧中變量s2指向的是對中一個變量t,t指向字符串常量池中的「abc」,因此s1和s2指向的地址不相同ui
s2.intern()獲取的是字符串的常量池中的地址,也就是若是變量直接指向常量池,那麼就是變量的地址,若是變量指向堆,那麼會獲取堆所指向字符串常量池中的地址this