MR-LI_20200903-李伟江

问题

StringBufferString新个人理解

昨晚没想到为什么 StringBuffer 实例不能相加 ,但是 String 实例可以相加。

  • 因为String是不可变的字符序列。一经创建,正常手段是不能修改底层的 final 修饰的 byte 数组的。

    + 是连接不可变的字符序列的 ,从而是可以连接的。连接后的字符序列是一个新的-不可变的-字符序列。

    通过 + 连接赋值的实例是不同的。

  • StringBuffer可变的字符序列 , 能通过 append方法来修改长度。由于StringBuffer继承了AbstractStringBuilder 类。

    • 这个类中的 value 、 coder 、 count 不是 final 修饰的 , 可以修改 。不是一个字符常量 ,不能连接。
        String str = "abc";
        System.out.println( str );
        System.out.println( str.hashCode() );
        System.out.println( System.identityHashCode( str ) );
        str += "c";
        str = str + "c";
        System.out.println( str );
        System.out.println( str.hashCode() );
        System.out.println( System.identityHashCode( str ) );
abc
96354
1562557367
abcc
2987073
1101288798
abccc
92599362
942731712

变量还是那个变量(str),实例却已经不是当初的实例 。

        StringBuffer sb = new StringBuffer();
        System.out.println( sb );
        System.out.println( sb.hashCode() );
        System.out.println( System.identityHashCode( sb ) );
        
        sb.append( "abcd  efg");
        System.out.println( sb );
        System.out.println( sb.hashCode() );
        System.out.println( System.identityHashCode( sb ) );

1101288798
1101288798
abcd  efg
1101288798
1101288798

变量还是同一个变量,实例还是同一个实例。从来都没有变过。

构造问题

public class Father {
    public String name;
    public Father() {
        System.out.println( this.name );
    }
    public void show() {
        System.out.println( this.name );
        System.out.println("this is show");
    }
}
public class Son extends Father {
    public Son() {
        super.name = "a";
        super.show();
    }
    public static void main(String[] args) {
        Son son = new Son();
    }
}

输出

null
a
this is show

可以证明的是,父类构造中的输出语句执行了,name的值也获取到了。

目前可以推断出,构造中的输出语句执行顺序在字段获取值 之前。

吐槽

《让子弹飞》看了不下五遍,每一次看都有不同的理解。电影的每一个细节和台词每次看都有不同的收获。

现在觉得java也是这样。同一个问题每一次看都有不同的理解。