==与equals最全解疑

两小儿辩==与equals;

 public static void main(String[] args) {
    // ==比较的是地址,equals比较的是内容,

    // 首先在integerCache中缓存127
    Integer a = 127;
    // 创建b时,先去缓存池查看是否有127的引用,有的话,直接拿来用
    Integer b = 127;

    // ==比较地址
    System.out.println(a == b);// true
    System.out.println(a.equals(b));// true

    // c和d都超出了integer的范围,这时,将不会在IntegerCache中缓存c或者d,相当于都是在内存中开辟新的地址
    Integer c = 128;
    Integer d = 128;
    System.out.println(c == d);// false
    System.out.println(c.equals(d));// true

    // 创建str1后,"hello,word"会被首先放在字符串缓存池中,缓存一个唯一的地址
    String str1 = "hello,word";
    // 这里创建str2时,会先去字符串缓存池寻找池内是否有相同的值,如果有的话,直接使用该缓存池已经存在的地址;
    String str2 = "hello,word";
    // 缓存一个唯一地址
    String str3 = "hello";
    // new会新开辟一块内存,用来指向新的string(对象)
    String str4 = new String(str3 + ",word");

    // ==比较的是地址,equals比较的是内容,
    System.out.println(str1 == str2);// true
    System.out.println(str1 == str4);// false
    System.out.println(str1.equals(str4));// true

}

猜你喜欢

转载自blog.csdn.net/Jatham/article/details/81453170