zoukankan      html  css  js  c++  java
  • JAVA中“==”和equals

     A."=="可用于基本类型和引用类型:

      当用于基本类型时候,是比较值是否相同;1==2; false;

      当用于引用类型的时候,是比较是否指向同一个对象。

     B.基本类型int、char、float等没有equals方法,equals只比较值(对象中的内容)是否相同(相同返回true)。

     C.一般的类,当没有重写equals方法时,equals()方法与“==”作用是相同的;

     D.对于String类较为特殊:

              String a = "abc"; String b="abc"; a==b 返回true,a.equals(b)返回true, 因为abc放在data区域;

          String a = new String("hello"); String b=new String("hello"); a==b是false(指向不同对象), 而a.equals(b)返回true(对象内容相同);

    E .更一般的,当equals()被重写时,往往用于对象的内容是否相同,请看下面的例子:

     1 public class TestEqual{
     2     public static void main(String[] args)
     3     {
     4         Cat c1 = new Cat(1, 2, 3);
     5         Cat c2 = new Cat(1, 2, 3);
     6         Cat c3 = new Cat(2, 2, 2);
     7         System.out.println(c1 == c2);//返回false 不指向同一个对象
     8         System.out.println(c1.equals(c2));//返回true 对象内容相同
     9         System.out.println(c1 == c3);//返回false 不指向同一个对象
    10         System.out.println(c1.equals(c3));//返回false 对象内容不同
    11     }
    12 }
    13 
    14 class Cat 
    15 {
    16     int color;
    17     int height, weight;
    18     
    19     public Cat(int color, int height, int weight) 
    20     {
    21         this.color = color;
    22         this.height = height;
    23         this.weight = weight;
    24     }
    25     
    26     public boolean equals(Object obj) 
    27     {
    28         if(obj == null) return false;
    29         else{
    30                 if(obj instanceof Cat)
    31                 {
    32                     Cat c = (Cat)obj;
    33                     if(c.color == this.color && c.height == this.height && c.weight == this.weight)
    34                     {
    35                         return true;
    36                     }
    37                 }
    38             }
    39         return false;
    40     }
    41     
    42 }
  • 相关阅读:
    python yaml文件数据按原有的数据顺序dump
    HTMLTestRunner
    os.path获取当前路径及父路径
    update 字符串拼接
    VSCode 快速生成.vue基本模板、发送http请求模板
    Vue取消eslint语法限制
    node-sass安装失败解决方法
    docker 创建mysql和redis
    阿里云镜像加速器地址
    .net core + xunit 集成测试
  • 原文地址:https://www.cnblogs.com/mu-tou-man/p/3792846.html
Copyright © 2011-2022 走看看