equals()与==的使用方法小结

                  关于equals()和==的使用区别

一、基本使用方法说明

      [1]对于String类而言,==是用来比较栈中的内存地址的,而equals是用来比较两个字符串所包含的内容是否相同。

      [2]对于非String类而言,==与equals()都是用来比较内存地址的。

      s1 = new String("abc");                               Student  s1 = new Student("abc");

      s2 = new String("abc");                               Student  s2 = new Student("abc");

      s3 = "abc";

      s4 = "abc";

      s3 == s4为true

      s1 == s2为false;                                          s1 ==s2 为false

      s1equals()s2为true                                       s1 equals()s2为false

      解释:对于两个类来说,s1与s2均为新创建的对象,因此变量地址是不一样的,而变量内容是一样的。

               对于String类而言,类中重写了equals()方法,用于比较字符串的内容。

               但如果在student类中加上s1 = s2,则输出结果均为false,因为此时两个地址相同

               对于s3和s4而言,两者均为"abc"创造的对象,所以地址相同

二、具体运用环境

      1、java中的八种基本类型比较大小只能使用==,不能使用equals();编译出错

      public class TestEquals {
      public static void main(String[] args)
      {
      int a = 3;
      int b = 4;
      int c = 3;
      System.out.println(a == b);//结果是false
      System.out.println(a == c);//结果是true
      System.out.println(a.equals(c));//错误,编译不能通过,equals方法
     //不能运用与基本类型的比较

      2、对于基本类型的包装类型,如Boolean、Character、Byte、Shot、Integer、Long、Float、Double,他们的用法与String类一样,==用来比较地址,而equals()用来比较内容

       public class TestEquals {
       public static void main(String[] args)
      {

       Integer n1 = new Integer(30);
       Integer n2 = new Integer(30);
       Integer n3 = new Integer(31);
       System.out.println(n1 == n2);//结果是false 

       System.out.println(n1 == n3);// 结果显示false
       System.out.println(n1.equals(n2));//结果是true

       System.out.println(n1.equals(n3));//结果是false

       }
}
其他的Double、Character、Float等也一样

     3、

       

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值