JDK源码阅读之二-----String
来源:互联网 发布:武汉学编程多久 编辑:程序博客网 时间:2024/05/17 20:32
package java.lang;import java.io.ObjectStreamClass;import java.io.ObjectStreamField;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.Formatter;import java.util.Locale;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException; // 我擦嘞,String类import了这么多包啊/** * Strings是固定不变的; 被创建后值就不能改变了. String buffers支持可变的strings. * Because String objects are immutable they can be shared. For example: * String str = "abc"; * 相当于: * char data[] = {'a', 'b', 'c'}; * String str = new String(data); * @see java.lang.Object#toString() * @see java.lang.StringBuffer * @see java.lang.StringBuilder * @see java.nio.charset.Charset 源码里让看这个,好吧,看完StringBuffer和StringBuilder就看看NIO吧 */public final class String implements java.io.Serializable, Comparable, CharSequence{ /** The value用来存储字符. */ private final char value[]; /** The offset is the first index of the storage that is used. */ private final int offset; /** count是字符数组的长度,final的,长度也不能变了. */ private final int count; /** Cache the hash code for the string */ private int hash; // Default to 0 // 构造方法很多,以后再补充吧 // 列举一些常见方法 /** * Returns the length of this string. */ public int length() { return count; } public boolean isEmpty() {return count == 0; } /** * @param index the index of the char
value. * @return the char
value at the specified index of this string. * The first char
value is at index 0
. * @exception IndexOutOfBoundsException if the index
* argument is negative or not less than the length of this * string. */ public char charAt(int index) { if ((index < 0) || (index >= count)) { throw new StringIndexOutOfBoundsException(index); } return value[index + offset]; } // 重写了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;while (n-- != 0) { if (v1[i++] != v2[j++])return false;}return true; }}return false; } // 重写hashcode方法 public int hashCode() {int h = hash; int len = count;if (h == 0 && len > 0) { int off = offset; char val[] = value; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; } public String toString() {return this; } public native String intern(); // 这个是干嘛滴}