zoukankan      html  css  js  c++  java
  • java 对象和基本数据类型 “==”区别

    “==”比较的是地址,牢记。
    1。对象。integer 是对象
    Integer i1 = 20;
    Integer i2 = 20 ;
    System.out.println(i1 == i2); // true
    Integer i3 = 200;
    Integer i4 = 200 ;
    System.out.println(i3 == i4); // false
    
    原因:Integer i1 = 20; 其实是一个自动装箱的过程,编译器会自动展开成Integer i = Integer.valueOf(20);详情可以看Integer.valueOf的源代码,可以看到参数的值在IntegerCache.low(默 认-128) 到 IntegerCache.high(默认127)范围内时(比如20),会从IntegerCache.cache中直接取(此处参考Integer的 内部类IntegerCache的源代码,如果不配置的话,默认是cache存储-128到127的Integer),所以取到的都是同一个 Integer的对象,因此相同。而200不在-128到127范围内,所以会new 一个新的Integer,故不相同。
     
    2.类型。int 是基本数据类型
     
    int i1=20;
    int i2=20;
    System.out.println(i1==i2);//true
    int i3=200;
    int i4=200;
    System.err.println(i3==i4);//true
    

    原因:i1 开辟了一个内存空间,对于i2来说,jvm先在内存中寻找是否有20的地址,有就给i2赋值,也就是让i2也指向20那块地址。所以返回的是TRUE.

    3.

    String str1 = "hello";
    String str2 = "he" + new String("llo");
    System.err.println(str1 == str2);
    

     返回的是false。

    原因:因为str2中的llo是新申请的内存块,而==判断的是对象的地址而非值,所以不一样。如果是String str2 = str1,那么就是true了。

     
     
     
     
  • 相关阅读:
    hdu 2199 Can you solve this equation? 二分
    STL 学习代码~
    hdu 1551 Cable master 二分
    fzu 1564 Combination 组合数是否包含因数
    fafu 1079 帮冬儿忙 组合数包含因数个数
    soj 3290 Distribute The Apples I 组合数对素数取余
    fzu 2020 组合 组合数对素数取余
    hdu 1969 Pie 二分
    hdu 2141 Can you find it? 二分
    hdu 2899 Strange fuction 二分
  • 原文地址:https://www.cnblogs.com/PopShow/p/5206504.html
Copyright © 2011-2022 走看看