Java String 的 equals() 方法可能的优化

1/5/2008来源:Java教程人气:4978


JDK1.4, 1.5 的 String Class 代码如下











[code]











public final class String











    implements java.io.Serializable, Comparable<String>, CharSequence











{











    /** The value is used for character storage. */











    PRivate final char value[];












 


 



 



    /** The offset is the first index of the storage that is used. */











    private final int offset;












 


 



 



    /** The count is the number of characters in the String. */











    private final int count;











[/code]












 


 



 



[code]











    /**











     * Initializes a newly created <code>String</code> object so that it











     * represents the same sequence of characters as the argument; in other











     * Words, the newly created string is a copy of the argument string. Unless











     * an eXPlicit copy of <code>original</code> is needed, use of this











     * constrUCtor is unnecessary since Strings are immutable.











     *











     * @param   original   a <code>String</code>.











     */











    public String(String original) {











            int size = original.count;











            char[] originalValue = original.value;











            char[] v;











            if (originalValue.length > size) {











                // The array representing the String is bigger than the new











                // String itself.  Perhaps this constructor is being called











                // in order to trim the baggage, so make a copy of the array.











                v = new char[size];











                System.arraycopy(originalValue, original.offset, v, 0, size);











            } else {











                // The array representing the String is the same











                // size as the String, so no point in making a copy.











                v = originalValue;











            }











            this.offset = 0;











            this.count = size;











            this.value = v;











    }











[/code]











从这段构造函数中,我们可以看出,不同Reference的String之间有可能共享相同的 char[]。