String类型是不可变类理解


Object的hashCode()默认是返回内存地址的,但是hashCode()可以重写,所以hashCode()不能代表内存地址的不同

System.identityHashCode(Object)方法可以返回对象的内存地址,不管该对象的类是否重写了hashCode()方法。

package com.question;

/**
 * @author kankan
 * @creater 2019-05-11 7:33
 */
public class Example {
    String str = new String("tarena");
    char[] ch = {'a','b','c'};

    public static void main(String[] args) {
        Example ex = new Example();
        ex.change(ex.str,ex.ch);
        System.out.println(ex.str);
        System.out.println("ex.str " + System.identityHashCode(ex.str));
        System.out.println(ex.ch);
        System.out.println("ex.ch " + System.identityHashCode(ex.ch));
    }

    private void change(String str, char[] ch) {
        str = "test ok";
        ch[0] = 'g';
        System.out.println("str " + System.identityHashCode(str));
        System.out.println("ch " + System.identityHashCode(ch));
    }
}

在这里插入图片描述
相当于在原有的基础上修改,但是当时String时,因为是不可变类,他不会在原来基础上修改,会新建一个。所以原地址还在,只是指向一个新地址

你可能感兴趣的:(程序员面试笔记)