Java源码之String-构造方法

1.public String() {
this.value = "".value;
}
直接赋空字符串

2.public String(String original) {
    this.value = original.value;
this.hash = original.hash;
}
将字符串的hash和value放入新的对象

3.
public String(char value[]) {
   this.value = Arrays.copyOf(value, value.length);
}
将char数组直接copy到String value属性

4.
public String(char value[], int offset, int count)
 首先判断 offset 和 count 值

 然后copy 字符数组的范围到String value

  5.public String(int[] codePoints, int offset, int count) 

    注意  char类型和int类型的编码!!!!

    第一步判断offset 和count 值

     

     第二步

  Character.isBmpCodePoint(c) 判断一个char 是否能够存储,能的话就不扩大char大小了

  Character.isValidCodePoint(c) 判断一个char是否不能够存,然后n++扩大char数组大小

  第三步:

  

  创建char字符数组然后遍历int数组, 如果int 属于Bmp 则直接存入,否则就需要拆分成高位和地位存储 

  6.public String(byte ascii[], int hibyte, int offset, int count) 弃用

  7.public String(byte ascii[], int hibyte) 弃用

  8.public String(byte bytes[], int offset, int length, String charsetName) 通过指定新的字符编码转换成字符串 

    核心:      

static char[] decode(String charsetName, byte[] ba, int off, int len)
throws UnsupportedEncodingException
{
StringDecoder sd = deref(decoder);  //获得StringDecoder类对象
String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;  //设置指定字符编码,默认ISO-8859-1
if ((sd == null) || !(csn.equals(sd.requestedCharsetName())
|| csn.equals(sd.charsetName()))) {
sd = null;
try {
Charset cs = lookupCharset(csn);
if (cs != null)
sd = new StringDecoder(cs, csn);
} catch (IllegalCharsetNameException x) {}
if (sd == null)
throw new UnsupportedEncodingException(csn);
set(decoder, sd);
}
return sd.decode(ba, off, len);
}

  9.public String(byte bytes[], int offset, int length, Charset charset)通过指定字符编码对象转换成字符串

    8,9点关于字节数组转换成字符数组,用到了Java封装的类StringCoding



原文地址:https://www.cnblogs.com/zyhzsq/p/13665984.html