java源码阅读-String类

public final class String
    implements java.io.Serializable, Comparable, CharSequence

实现了序列化和比较器

    /** The value is used for character storage. */
    private final char value[];

这个属性是用来存储string中的内容的

   /** Cache the hash code for the string */
   private int hash; // Default to 0

缓存hashcode

//不带参数初始化
    public String() {
        this.value = "".value;
    }
   //拷贝初始化
    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
//字符数组初始化
    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);
    }
//StringBuffer构造
  public String(StringBuffer buffer) {
        synchronized(buffer) {
            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
        }
    }
//builder构造
    public String(StringBuilder builder) {
        this.value = Arrays.copyOf(builder.getValue(), builder.length());
    }

比较每一位上面的字符是否相同

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;
    }

无视大小写比较

 public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true
                : (anotherString != null)
                && (anotherString.value.length == value.length)
                && regionMatches(true, 0, anotherString, 0, value.length);
    }

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;
    }

返回常量池中的string 全局唯一

    public native String intern();

你可能感兴趣的:(java源码阅读-String类)