java == 与equal 的区别

==

         

  1. 判定的是对象的等价性,必须是实实在在地是同一个对象才返回true
  2. 判定基本型的值是否相等。
      
int i1 = 47;
int i2 = 47;
System.out.println(i1 == i2); //output: true
//基本型包装类
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1 == n2); //output: false
//String大人
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); //output: false



equal 
          equals()是可以判定对象内容的方法。但不能用于基本型。而且要用这个方法,必须自己重载。不然他默认只是从普通类object继承下来的,还是比较对象的 “引用”,也就 是内存地址。
   
1
2
3
4
5
6
7
8
9
10
11
//Value类型的object没有被重载(调教)过。当然不能比较值的大小。
class Value {
      public int i;
      
      public static void main(String[] args) {
        Value v1 = new Value();
        Value v2 = new Value();
        v1.i = v2.i = 100;
        System.out.println(v1.equals(v2)); //output: false
      }
}

JDK自带重载好equals()方法的类很少。最常用的就是String以及基本型的包装类,比如Integer。

1
2
3
4
5
6
7
8
//基本型包装类
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(n2)); //output: true
//String大人
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2)); //output: true


         

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值