抱紧你的我,比国王富有.失去你的我,比乞丐落魄. -- 国王与乞丐(歌曲)
记录一下今天看的String 的源码. 这里看完之后还是有很深的感触,当然也有很多地方是没有看明白和想明白的.
1 : 属性介绍
// The value is used for character storage. 用于字符存储
private final char value[];
// Cache the hash code for the string 默认是0
private int hash;
private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0]; // 内部类的new public static final Comparator<String> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator();
2 : 内部类
// 内部类的名字
CaseInsensitiveComparator
// 返回String 中 定义的属性
private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
// 获取 s1,s2 中最短的一个,根据二者中最短的长度来进行迭代。然后进行 大写或者小写的比较,返回二者比较的相互减去的值。
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) { // No overflow because of numeric promotion return c1 - c2; } } } } return n1 - n2; }
3 : 构造方法介绍 ; 过时的构造方法就不做记录了
// 无参构造,默认给 value 赋值为"" 空字符串 public String() { this.value = "".value; }
// Sring 构造方法 public String(String original) { this.value = original.value; this.hash = original.hash; }
// char 数组的构造方法。 使用 Arrays.copyOf()的Api来复制一个新的char 然后让this.value 属性等于新赋值出来的char数组 public String(char value[]) { this.value = Arrays.copyOf(value, value.length); }
// char 数组 ; offset 开始的坐标, count 个数. 先检查条件,然后使用Arrays.copyOfRange来进行范围复制 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); }
// 传入int 数组 开始的下标和个数 与上面不同的是,这里做完条件检查,还多了Character之类的操作,然后新new一个char 来存储数据数据,大小是n,然后赋值给this.value.
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[] int n = count; for (int i = offset; i < end; i++) { int c = codePoints[i]; if (Character.isBmpCodePoint(c)) continue; else if (Character.isValidCodePoint(c)) n++; else throw new IllegalArgumentException(Integer.toString(c)); } // Pass 2: Allocate and fill in 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)) v[j] = (char)c; else Character.toSurrogates(c, v, j++); } this.value = v; }
// 使用byte 数组,开始下标和长度,编码类型(个人认为可能是类似于UTF8那种) 调用checkBounds 来检查是否符合要就,然后就调用 StringCoding.decode 来生成新的char 数组,然后赋值给this.value. 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[], 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[]) { this(bytes, 0, bytes.length); }
// 这是传入StringBuffer 的构造函数,使用了同步进行线程安全的控制。 public String(StringBuffer buffer) { synchronized(buffer) { this.value = Arrays.copyOf(buffer.getValue(), buffer.length()); } }
// StringBuilder 来进行构造函数 ; 这里没有使用 synchronized 来进行同步. public String(StringBuilder builder) { this.value = Arrays.copyOf(builder.getValue(), builder.length()); }
4 : 方法的介绍 ; 由于有些方法之间的相互调用是通过重载的,也就不会每一个方法都会记录到.主要是记录那些核心的.
// 返回 String 的长度,也就是利用存储 String 内容的char数组的长度 public int length() { return value.length; }
// 判断其长度是否为0 这里不能判断是否null public boolean isEmpty() { return value.length == 0; }
// 返回 index 下标的char 先对index 进行长度的检查;如果符合条件就直接从数组中拿取. public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }
// 这个equals 应该是我们用String使用到最多的api了吧,毕竟是动不动就要做比较是否相同的判断.先使用this来进行判断的比较 // 判断传入进来的参数是否是String 类型,如果是就强转为String 类型 如果长度相同就进入比较每个坐标下的char是否相同 public boolean equals(Object anObject) { if (this == anObject) { 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]) return false; i++; } return true; } } return false; }
// 比较String 和 CharSequence是否完全相同, 如果 cs 是 StringBuffer ;就会进行同步;然后调nonSyncContentEquals // 然后先判断长度是否相同,如果长度相同的话,就会比较每个char 的值是相同 public boolean contentEquals(CharSequence cs) { // Argument is a StringBuffer, StringBuilder if (cs instanceof AbstractStringBuilder) { if (cs instanceof StringBuffer) { synchronized(cs) { return nonSyncContentEquals((AbstractStringBuilder)cs); } } else { 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 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++; } return len1 - len2; }
// 判断是否开头部分包含;从 toffset 开始; startsWith 和 endsWith 方法都对这个进行重载了. // 现将value 使用一个新的char 数组来进行标记,传入进来的String 和 toffset 都分别使用二个新的来定义,先对长度来进行判断 如果小于0或者比我大肯定不是以我开头的,返回false.然后对传入进来的String 长度的进行遍历,然后和value中的根据下标来进行对象,如果不是一样的,就是会返回false.否则就是符合要求的,返回true. 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; }
// 对上面的api进行重载 public boolean startsWith(String prefix) { return startsWith(prefix, 0); }
public boolean endsWith(String suffix) { return startsWith(suffix, value.length - suffix.value.length); }
// 来啦,返回hashCode的api来了。 // 这里就是遍历String 在外面标记一个变量h;来进行每次对每个 31*h +val[i] (这是char) 相加赋值给 h。一直到最后,赋值给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 = h; } return h; }
// 如果满足条件的话,就会返回相应的下标值大小 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 { return indexOfSupplementary(ch, fromIndex); } }
// 这里的参数比较多,"123".indexOf("1") 举一个这样的操作,来对参数进行说明会好点. // source 对应 1,2,3的char数组 sourceOffset 1,2,3中开始的下标,sourceCount的长度 // target 就是 1的char数组 targetOffset 的开始下标,targetCount个数,fromIndex从那个index开始. // 在for 之前都会对长度之类的进行检查. 取出 target 下标是targetOffset的char标记为first.如果source 开始不是在 first相同的char开始的话,那么 while 中就会做一个 i++ ; 直到下标的char对应上first相同.最后用 j,k 来标记二个char的下标,来判断比较是否相同,如果有的话 就会返回对应的下标的数字之类的,如果没有的话,就会返回-1. 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; }
// 从 beginIndex 截取到endIndex ; 但是不包含endIndex.先对长度进行检查,然后根据条件来判断是否调用构造方法. 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); }
// 对String 进行拼接,返回新的String 主要就是调用 Arrays.copyOf 和 str.getChars()来进行char 数组的操作 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 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;
好啦,今天就记录到这里,还有很多其他的api都是进行重载或者类似Integer 转化为String , 其实就是调动Integer.toString(值)来进行转换的.