String源码分析(一部分方法)

来源:互联网 发布:软件调试的目的 编辑:程序博客网 时间:2024/06/06 09:17
1、String不能被继承
会出现The type TestString cannot subclass the final class String错误。
查看源码
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
String类被final修饰,不能被继承。同时实现了几个接口。
2、
 /** The value is used for character storage. */
   privatefinalcharvalue[];
定义一个储存字符的变量,不过这个变量被final修饰,说明这个变量不可被改变。
3、
String str = new String();//注意,由于字符串是不可变的,所以使用此构造函数是不必要的。
4、
   /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
   public String() {
       this.value= "".value;
    }
除非需要显式的复制{@code original},否则使用此构造器是没有必要的,因为String字符串是不可变的。
5、String对equals方法的重写:将字符串中每个字符摘取出来比较,如果全部相等,则返回true
 
    /**
     * 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;
    }

6、字符串忽略大小写的核心代码:
①、首先说一下为什么要比较完大写还要比较小写:因为在某些字母里面,例如格鲁吉亚字母表,转换大写是无效的,只能通过再次比较小写来判断。
②、最后小写比较大小:因为两个字符串长度不相同,但小写的字符相等,就会返回0。
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;
        }

7、compareTo()方法的核心代码:比较相同位置字符的大小,不忽略大小写。
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;
    }


8、regionMatches():匹配字符串
publicbooleanregionMatches(booleanignoreCase,inttoffset,
            Stringother,intooffset,intlen) {
       charta[] =value;
       intto=toffset;
       charpa[] =other.value;
       intpo=ooffset;
       // Note: toffset, ooffset, or len might be near -1>>>1.
       if((ooffset< 0) || (toffset< 0)
                || (toffset> (long)value.length-len)
                || (ooffset> (long)other.value.length-len)) {
           returnfalse;
        }
       while(len-- > 0) {
           charc1=ta[to++];
           charc2=pa[po++];
           if(c1==c2) {
               continue;
            }
           if(ignoreCase) {
               // If characters don't match but case may be ignored,
               // try converting both characters to uppercase.
               // If the results match, then the comparison scan should
               // continue.
               charu1= Character.toUpperCase(c1);
               charu2= Character.toUpperCase(c2);
               if(u1==u2) {
                   continue;
                }
               // Unfortunately, conversion to uppercase does not work properly
               // for the Georgian alphabet, which has strange rules about case
               // conversion.  So we need to make one last check before
               // exiting.
               if(Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                   continue;
                }
            }
           returnfalse;
        }
       returntrue;
    }


9、替换字符串中的某个字符
publicString replace(charoldChar,char newChar) {
       if (oldChar!= newChar) {
           int len = value.length;
           int i = -1;
           char[]val = value;/* avoid getfield opcode */

           while (++i< len) {
                //如果字符串中的某个字符与旧字符相等,则退出循环,获得旧字符在字符串中的位置。
               if (val[i] == oldChar) {
                   break;
                }
            }
           if (i< len) {
               char buf[] =new char[len];
                //将第一个匹配的旧字符位置之前的字符复制到新的字符数组中。
               for (intj = 0; j < i;j++) {
                   buf[j] = val[j];
                }
               while (i< len) {
                   char c = val[i];
                   buf[i] = (c== oldChar) ?newChar : c;
                   i++;
                }
               return new String(buf,true);
            }
        }
       return this;
    }