zoukankan      html  css  js  c++  java
  • Java中“==”和equals()方法

    这是在Thinking in Java中看到的。

    第一个程序

    1 public class Exponents {
    2     public static void main(String []args){
    3         Integer n1=new Integer(47);
    4         Integer n2=new Integer(47);
    5         System.out.println(n1==n2);
    6         System.out.println(n1!=n2);
    7     }
    8 }

    输出结果:

    1 false
    2 true

    Java中声明的类对象都是引用,n1、n2的内容相同,但两者指向不同的存储位置。

    第二个程序

    1 public class Exponents {
    2     public static void main(String []args){
    3         Integer n1=new Integer(47);
    4         Integer n2=new Integer(47);
    5         System.out.println(n1.equals(n2));
    6     }
    7 
    8 }

    输出结果:true

    equals()方法默认的行为是比较引用。但大多数Java类库都实现了equals方法用来比较对象的内容,而非比较对象的引用。

    第三个程序:

     1 class Value{
     2     int i;
     3 }
     4 public class Exponents {
     5     public static void main(String []args){
     6         Value v1=new Value();
     7         Value v2=new Value();
     8         v1.i=v2.i=100;
     9         System.out.println(v1.equals(v2));
    10     }
    11 
    12 }

    输出结果:false

    自己定义的类,需要覆盖equals()方法。

  • 相关阅读:
    当数据库遇上外键
    java EE实现动态SQL的
    Java EE注册三部曲(一步曲)
    xml+js+html的二级联动
    MySQL中like的使用方法
    oracle 外部表查alter日志
    oracle 预安装命令
    LINUX 安装增强 前置安装文件
    linux 6.5 网卡
    liunux 6.5设置网卡默认开启
  • 原文地址:https://www.cnblogs.com/xianzhedeyu/p/3506444.html
Copyright © 2011-2022 走看看