jdk1.6学习笔记

来源:互联网 发布:大数据mobi 编辑:程序博客网 时间:2024/05/22 09:52

从今天开始学习jdk1.6,虽然有点老了,但是还是有必要学习下的。

首先第一个类,也是经常用到的String。

String类在java.lang包中。定义为public final class String,此类有四个属性分别是char数组value[],int型offset,int型count,int型hash。

value是字符串对应的字符数组值,offset是一个位置标记量,count是String对象的数组元素的长度,hash是String类型的hashcode。

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.            int off = original.offset;            v = Arrays.copyOfRange(originalValue, off, off+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;    }

这是一个java的构造函数形如 String a = new String("abc");此类创建对象会调用此构造函数,这个构造函数中if判断说original的字符数组的长度大于字符串的count时候

对字符数组进行一个新的拷贝,否则直接指向以前的字符数组。这个不是很理解,我直观感觉这两个变量应该是同一个字符串的长度和字符串的字符数组的长度进行比较应该像等的啊,但是有一次面试时候,面试官说这种类型的创建string对象其实是对字符串的一个拷贝,the
     * newly created string is a copy of the argument string,这一句也说明了它是对原有字符串的一个拷贝。有点不能理解。。。。希望有明白的同学指点一下。


0 0