String源码解析(二)

时间:2022-05-23 00:48:40

方法的主要功能看代码注释即可,这里主要看函数实现的方式。

1.getChars(char dst[], int dstBegin)

     /**
      * Copy characters from this string into dst starting at dstBegin.
      * This method doesn't perform any range checking.
      */
     void getChars(char dst[], int dstBegin) {
         System.arraycopy(value, 0, dst, dstBegin, value.length);
     }

该方法将调用该方法的字符串拷贝到字符数组dst中,从dstBegin开始存放,拷贝length字节。

该方法默认是包范围的,而且不进行边界检查。

2.getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

     /**
      * Copies characters from this string into the destination character
      * array.
      * <p>
      * The first character to be copied is at index {@code srcBegin};
      * the last character to be copied is at index {@code srcEnd-1}
      * (thus the total number of characters to be copied is
      * {@code srcEnd-srcBegin}). The characters are copied into the
      * subarray of {@code dst} starting at index {@code dstBegin}
      * and ending at index:
      * <blockquote><pre>
      *     dstBegin + (srcEnd-srcBegin) - 1
      * </pre></blockquote>
      *
      * @param      srcBegin   index of the first character in the string
      *                        to copy.
      * @param      srcEnd     index after the last character in the string
      *                        to copy.
      * @param      dst        the destination array.
      * @param      dstBegin   the start offset in the destination array.
      * @exception IndexOutOfBoundsException If any of the following
      *            is true:
      *            <ul><li>{@code srcBegin} is negative.
      *            <li>{@code srcBegin} is greater than {@code srcEnd}
      *            <li>{@code srcEnd} is greater than the length of this
      *                string
      *            <li>{@code dstBegin} is negative
      *            <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
      *                {@code dst.length}</ul>
      */
     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(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
     }

该方法先对srcBegin、srcEnd进行了边界检查,然后调用System.arraycopy实现复制。

3.getBytes()

     /**
      * Encodes this {@code String} into a sequence of bytes using the named
      * charset, storing the result into a new byte array.
      *
      * <p> The behavior of this method when this string cannot be encoded in
      * the given charset is unspecified.  The {@link
      * java.nio.charset.CharsetEncoder} class should be used when more control
      * over the encoding process is required.
      *
      * @param  charsetName
      *         The name of a supported {@linkplain java.nio.charset.Charset
      *         charset}
      *
      * @return  The resultant byte array
      *
      * @throws  UnsupportedEncodingException
      *          If the named charset is not supported
      *
      * @since  JDK1.1
      */
     public byte[] getBytes(String charsetName)
             throws UnsupportedEncodingException {
         if (charsetName == null) throw new NullPointerException();
         return StringCoding.encode(charsetName, value, 0, value.length);
     }

     /**
      * Encodes this {@code String} into a sequence of bytes using the given
      * {@linkplain java.nio.charset.Charset charset}, storing the result into a
      * new byte array.
      *
      * <p> This method always replaces malformed-input and unmappable-character
      * sequences with this charset's default replacement byte array.  The
      * {@link java.nio.charset.CharsetEncoder} class should be used when more
      * control over the encoding process is required.
      *
      * @param  charset
      *         The {@linkplain java.nio.charset.Charset} to be used to encode
      *         the {@code String}
      *
      * @return  The resultant byte array
      *
      * @since  1.6
      */
     public byte[] getBytes(Charset charset) {
         if (charset == null) throw new NullPointerException();
         return StringCoding.encode(charset, value, 0, value.length);
     }

     /**
      * Encodes this {@code String} into a sequence of bytes using the
      * platform's default charset, storing the result into a new byte array.
      *
      * <p> The behavior of this method when this string cannot be encoded in
      * the default charset is unspecified.  The {@link
      * java.nio.charset.CharsetEncoder} class should be used when more control
      * over the encoding process is required.
      *
      * @return  The resultant byte array
      *
      * @since      JDK1.1
      */
     public byte[] getBytes() {
         return StringCoding.encode(value, 0, value.length);
     }

这个三个方法都是将String编码为byte序列存储到byte数组后返回,都是调用StringCode.encode方法实现。

方法的不同之处是字符集指定方式,分别是字符集名字、字符集和平台默认字符集。

4.equals(Object anObject)

     /**
      * Compares this string to the specified object.  The result is {@code
      * true} if and only if the argument is not {@code null} and is a {@code
      * String} object that represents the same sequence of characters as this
      * object.
      *
      * @param  anObject
      *         The object to compare this {@code String} against
      *
      * @return  {@code true} if the given object represents a {@code String}
      *          equivalent to this string, {@code false} otherwise
      *
      * @see  #compareTo(String)
      * @see  #equalsIgnoreCase(String)
      */
     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;
     }

此方法将字符串与指定的对象anObject比较。

从代码中我们可以看出:

  先使用==进行判断,这是对字节码进行判断,如果二者相同则返回true;

  然后再判断anObject是否是一个String的一个实例,这是继续向下比较的条件;

  如果anObject是一个String实例,则转换为String;

  接下来比较两个字符串的长度,如果长度相等,再将两个字符串转换为char数组,对比相应位置上的元素。

  只有类型、长度和元素都相等的情况下才返回true。

5.contentEquals(StringBuffer sb)

   /**
      * Compares this string to the specified {@code StringBuffer}.  The result
      * is {@code true} if and only if this {@code String} represents the same
      * sequence of characters as the specified {@code StringBuffer}. This method
      * synchronizes on the {@code StringBuffer}.
      *
      * @param  sb
      *         The {@code StringBuffer} to compare this {@code String} against
      *
      * @return  {@code true} if this {@code String} represents the same
      *          sequence of characters as the specified {@code StringBuffer},
      *          {@code false} otherwise
      *
      * @since  1.4
      */
     public boolean contentEquals(StringBuffer sb) {
         return contentEquals((CharSequence)sb);
     }

该方法将字符串与一个StringBuffer对象进行比较,具体的比较操作是调用contentEquals()方法实现的。

6.contentEquals(CharSequence cs)

   /**
      * Compares this string to the specified {@code CharSequence}.  The
      * result is {@code true} if and only if this {@code String} represents the
      * same sequence of char values as the specified sequence. Note that if the
      * {@code CharSequence} is a {@code StringBuffer} then the method
      * synchronizes on it.
      *
      * @param  cs
      *         The sequence to compare this {@code String} against
      *
      * @return  {@code true} if this {@code String} represents the same
      *          sequence of char values as the specified sequence, {@code
      *          false} otherwise
      *
      * @since  1.5
      */
     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;
     }

该方法的参数是一个字符序列cs,只进行内容的比较:

  如果cs是AbstractStringBuilder实例但不是StringBuffer实例,直接调用方法nonSyncContentEquals()进行比较;

  如果cs是StringBuffer实例,也是调用方法nonSyncContentEquals()实现比较,但是需要synchronized同步;

  如果cs不是AbstractStringBuilder实例,但是一个String实例,调用方法equals()实现比较;

  如果cs只是一个普通的字符序列,比较序列长度和对应位置字符相等就可以了。

7.nonSyncContentEquals(AbstractStringBuilder sb)

 private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
         char v1[] = value;
         char v2[] = sb.getValue();
         int n = v1.length;
         if (n != sb.length()) {
             return false;
         }
         for (int i = 0; i < n; i++) {
             if (v1[i] != v2[i]) {
                 return false;
             }
         }
         return true;
     }

这是一个私有方法。

从方法名就可以看出这是一个非同步比较方法,参数是AbstractStringBuilder类型。

比较时,也只是从AbstractStringBuilder取出字符数组,然后和调用者的字符数组进行比较。

综上,我们可以看到,不同的equals函数实现不同的判等方式,比如:

只进行存储内容的判断,而不比较类类型;

不但进行类型的判断,还要对存储内容进行判断;

...