Java基础之String

1、String类

想要了解一个类,最好的办法就是看这个类的实现源代码,String类的实现在\jdk1.6.0_14\src\java\lang\String.java 文件中。打开这个类文件就会发现String类是被final修饰的:

public final class String
    implements java.io.Serializable, Comparable, 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; 
    /** Cache the hash code for the string */
    private int hash; // Default to 0 
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L; 
    ...... 
}

从上面可以看出几点:

  1. String类是final类,也即意味着String类不能被继承,并且它的成员方法都默认为final方法。在Java中,被final修饰的类是不允许被继承的,并且该类中的成员方法都默认为final方法。在早期的JVM实现版本中,被final修饰的方法会被转为内嵌调用以提升执行效率。而从Java SE5/6开始,就渐渐摈弃这种方式了。因此在现在的Java SE版本中,不需要考虑用final去提升方法调用效率。只有在确定不想让该方法被覆盖时,才将方法设置为final。
  2. 上面列举出了String类中所有的成员属性,从上面可以看出String类其实是通过char数组来保存字符串的。

下面再继续看String类的一些方法实现:

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
        throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
    }
    return ((beginIndex == 0) && (endIndex == count)) ? this :
        new String(offset + beginIndex, endIndex - beginIndex, value);
    }
 
 public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    char buf[] = new char[count + otherLen];
    getChars(0, count, buf, 0);
    str.getChars(0, otherLen, buf, count);
    return new String(0, count + otherLen, buf);
    }
 
 public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        int len = count;
        int i = -1;
        char[] val = value; /* avoid getfield opcode */
        int off = offset;   /* avoid getfield opcode */
 
        while (++i < len) {
        if (val[off + i] == oldChar) {
            break;
        }
        }
        if (i < len) {
        char buf[] = new char[len];
        for (int j = 0 ; j < i ; j++) {
            buf[j] = val[off+j];
        }
        while (i < len) {
            char c = val[off + i];
            buf[i] = (c == oldChar) ? newChar : c;
            i++;
        }
        return new String(0, len, buf);
        }
    }
    return this;

从上面的三个方法可以看出,无论是sub操、concat还是replace操作都不是在原有的字符串上进行的,而是重新生成了一个新的字符串对象。也就是说进行这些操作后,最原始的字符串并没有被改变。在这里要永远记住一点:
对String对象的任何改变都不影响到原对象,相关的任何change操作都会生成新的对象

2、深入理解String

先看如下代码:

public class Main { 
    public static void main(String[] args) {
        String str1 = "abcd";//line 1
        String str2 = new String(str1);// line 2
        String str3 = "abcd";//line 3
        String str4 = new String("abcd"); //line 4
        String str5 = str1;//line 5
        str5 = str5.concat("ef");//line 6
        System.out.println(str1==str3);        
        System.out.println(str1==str2);              
        System.out.println(str2==str4);        
        System.out.println(str1==str5);
        System.out.println(str1.equals(str3));
        System.out.println(str1.equals(str2)); 
        System.out.println(str2.equals(str4));
        System.out.println(str1.equals(str5));
    }
}

这些语句会发生什么事情? 大概是这样的:

  1. line 1 line 3:分配一个长度为4的char数组,并在常量池分配一个由这个char数组组成的字符串,然后由str1去引用这个字符串。用str3去引用常量池里边的字符串,所以str1和str3引用的是同一个对象。
  2. line 2:在堆内存中开辟一个新的空间,但内部的字符数组引用着str1内部的字符数组。
  3. line 4:同样会在堆内存中开辟一个新的空间,但内部的字符数组引用常量池里边的字符串内部的字符数组,意思是和str2是同样的字符数组。
    这段代码的输出结果为:true,fasle,fase,false,true,true,true,false。原因解释如下:
    对于结果一:
    字符串池是方法区中的一部分特殊存储。当一个字符串被被创建的时候,首先会去这个字符串池中查找,如果找到,直接返回对该字符串的引用。
    图示如下:
    Java基础之String_第1张图片
    String.png

    对于结果四,图示如下:
  • 定义一个字符串:


    Java基础之String_第2张图片
    String-1.jpeg
  • 使用变量来赋值变量:


    Java基础之String_第3张图片
    String-2.jpeg
  • 字符串连接:


    Java基础之String_第4张图片
    string-3.jpeg

str5中保存的是一个重新创建出来的string对象的引用。

对于结果二、三:
总所周知,通过new关键字来生成对象是在堆区进行的,而在堆区进行对象生成的过程是不会去检测该对象是否已经存在的。因此通过new来创建对象,创建出的一定是不同的对象,即使字符串的内容是相同的。

对于equals比较结果:
解释参见下一篇博客Java基础之equals方法

3、总结

特别要注意的是,String类是通过char数组来保存字符串的,即字符串内部是通过字符数组存储的,String类的所有方法都没有改变字符串本身的值,都是返回了一个新的对象。

你可能感兴趣的:(Java基础之String)