• Java中equals方法和==的区别


    这个java基础一直记不清楚,这次总结下,与大家共勉。

    先上结论:

    1、equals方法比较两个对象的内容

    2、==比较两个对象是否是同一对象,或者说对象在内存中的首地址是否相同

    测试代码:

    /**
     * equals 和 == 的区别
     *
     * @author FlyFive(pengfei.dongpf@gmail.com)
     * created on 2013-1-5
     */
    public class EqualsTest {
        public static void main(String[] args) {
            String s01 = new String("hello world");
            String s02 = new String("hello world");
            System.out.println("两个new出来的String");
            System.out.println(s01.equals(s02));
            System.out.println(s01 == s02);
            
            String s11 = new String("hello world");
            String s12 = s11;
            System.out.println("两个相同的String");
            System.out.println(s11 == s12);
            System.out.println(s11 == s12);
            
            String s21 = "hello world";
            String s22 = "hello world";
            System.out.println("两个直接赋值的String");
            System.out.println(s21.equals(s21));
            System.out.println(s21 == s22);
            
            Object s31 = new Object();
            Object s32 = new Object();
            System.out.println("两个new出来的普通对象");
            System.out.println(s31.equals(s31));
            System.out.println(s31 == s32);
            
            Integer s41 = new Integer(1);
            Integer s42 = new Integer(1);
            System.out.println("两个new出来的基本类型包装类");
            System.out.println(s41.equals(s41));
            System.out.println(s41 == s42);
            
            
        }
    }

    测试结果:

    两个new出来的String
    true
    false
    两个相同的String
    true
    true
    两个直接赋值的String
    true
    true
    两个new出来的普通对象
    true
    false
    两个new出来的基本类型包装类
    true
    false

    注:

    由于s21和s22是两个字符串常量所生成的变量,其中所存放的内存地址是相同的,

    原文链接:http://www.cnblogs.com/FlyFive/archive/2013/01/05/2845314.html

  • 相关阅读:
    C++读写文件并排序
    我的vim配置---jeffy-vim-v2.2.tar
    vim 代码注释插件
    我的vim配置---jeffy-vim-v2.1.tar
    linux中screen命令的用法
    Install and Enable Telnet server in Ubuntu Linux
    Telnet环境变量
    Telnet窗口尺寸选项
    TELNET终端类型选项
    Telnet技术白皮书
  • 原文地址:https://www.cnblogs.com/FlyFive/p/2845314.html
Copyright © 2020-2023  润新知