一些基本方法的原理异同

今天看了下几个朋友的博客,发现了自己的一个盲点,最后看源码时发现了一件有趣的事:

public static void main(String[] args) {
		char[]chars= {'r','b','o','t'};
		//打印地址符
		//System.out.println(chars.toString());
		//以数组集合方式打印
		//String string = Arrays.toString(chars);
		***

## //将数组内容按序连接然后输出 //String string = new String(chars); String string = new String(); for (int i = 0; i < chars.length; i++) { string += Character.toString(chars[i]); } System.out.println(string); }```

***
重点看加粗的地方,两种方式都是实现的相同作用,当时我挺奇怪的,然后我们来看源码:`

``
public String(char value[]) {
        this(value, 0, value.length, null);//第一种方法的
    }
     String(char[] value, int off, int len, Void sig) {
        if (len == 0) {
            this.value = "".value;
            this.coder = "".coder;
            return;
        }
        if (COMPACT_STRINGS) {
            byte[] val = StringUTF16.compress(value, off, len);
            if (val != null) {
                this.value = val;
                this.coder = LATIN1;
                return;
            }
        }
      

## this.coder = UTF16; this.value = StringUTF16.toBytes(value, off, len);

    }
    //第二种方法的
    public String() {
        this.value = "".value;
        this.coder = "".coder;
    }
     public static String toString(char c) {
        return String.valueOf(c);
    }
 public static String valueOf(char c) {
        if (COMPACT_STRINGS && StringLatin1.canEncode(c)) {
            return new String(StringLatin1.toBytes(c), LATIN1);
        }
       

## return new String(StringUTF16.toBytes(c), UTF16);

    }

两种方法使用的构造器不同使用的外层封装方法不同,但是底层源码却是完全相同

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值