`
cjsmq
  • 浏览: 14275 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

java String

阅读更多
java String 源码

String 类底层是 char 类型数组实现的。

String 类API 文档描述如下:
String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例来实现。

字符串是常量;它们的值在创建之后不能改变。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享它们。例如:


   
   
    String str = "abc";
   
等效于:
   
 
     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
   

   
讨论 String的值为什么不可变:
String类被定义为 final ,且jdk的API中没有提供可以更改char[]值的方法。
至于substring 、replace 方法等均是重新生成一个新的String对象,而并不改变原先对象。

java语言 String中有字符串常量池的概念:

    
    String s1 = "hello";
    String s2 = "hello";
 


String类有一个特殊的创建方法,就是使用""双引号来创建
上述的代码创建String 实例步骤

1.查看常量池中是否存在内容为 hello 的相同字符串对象

2.若没有,就在常量池中创建一个包含该内容的字符串对象,并让引用变量指向该对象

3若已经存在,则让字符串引用直接指向常量池中对象

上例中 s1==s2 为true;

    
     String s3 = new String("hello world");
     String s4 = "hello world";


String s3 = new String("hello world")
实际创建了2个String对象,一个是"hello world"通过""双引号创建的,另一个是通过new创建的.只不过他们创建的时期不同,一个是编译期,一个是运行期!
这时 s3 == s4 为false;两个不同的对象。


再看 String 类定义:


public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** The value is used for character storage. */
    //底层维护的是char 数组。
    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



String 重写了equals方法:


   
 public boolean equals(Object anObject) { 
         //比较地址
	if (this == anObject) {
	    return true;
	}
	if (anObject instanceof String) {
	    String anotherString = (String)anObject;
	    int n = count;
	    if (n == anotherString.count) {
		char v1[] = value;
		char v2[] = anotherString.value;
		int i = offset;
		int j = anotherString.offset;
                  //比较两字符串char[]数组里的值。一一对应比较。
		while (n-- != 0) {
		    if (v1[i++] != v2[j++])
			return false;
		}
		return true;
	    }
	}
	return false;
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics