String 和Integer中 == 和 equals的使用

equals的作用:用于判断两个变量是否是对同一个对象的引用,即堆中的内容是否相同,返回值为布尔类型

“==”操作符的作用:
1、用于基本数据类型的比较
2、判断引用是否指向堆内存的同一块地址。

 public static void main(String[] args){
        String a = "Hello";
        String b = "Hello";
        String c = new String("Hello");
        String d = new String("Hello");
        /**String作为一个基本类型来使用**/
        System.out.println(a==b);//ture
        System.out.println(a.equals(b));//true

        System.out.println(a==c); //false
        System.out.println(a.equals(c)); //true
        /**String作为引用类型来使用**/
        System.out.println(c == d); //引用不同,false
        System.out.println(c.equals(d)); //内容相同,true
    }
public static void main(String[] args) {
        Integer a = 150;
        Integer b = 150;
        Integer c = new Integer(150);
        Integer d = new Integer(150);
        int e = 150;
        System.out.println(a==b); //false
        System.out.println(a.equals(b));//true
        System.out.println(a==c);//false
        System.out.println(a.equals(c));//true
        System.out.println(c==d);//false
        System.out.println(c.equals(d));//true
        //因为与初始化值做比较的时候,会将封装类型进行拆箱操作,转换为基本类型。这里比较的就是基本类型的值了*
        System.out.println(a==e);//true
        System.out.println(a.equals(e));//true
        System.out.println(c==e);//true
        System.out.println(c.equals(e));//true
    }
public int intValue() {
        return value;
}

其中有个特例:

public static void test(){
      Integer a=1;
      Integer b=1;
      System.out.println(a==b); //true
      System.out.println(a.equals(b));//true
  }
Integer a=150;//会将int类型通过valueof转换成Integer类型。下面是valueof源码。
static final int low = -128;
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

也就是说在-128到127之间的值会缓存到IntegerCache.cache中,所以在Integer x=在-128到127之间时,返回的是同一个对象,所以出现了上文的情况。(如果换成 >、>=、<、<=会出现什么情况呢?这中情况会自动拆箱比较值。)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值