OOP 中的同一性和平等性有什么区别? [英] What is the difference between identity and equality in OOP?

查看:30
本文介绍了OOP 中的同一性和平等性有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OOP(面向对象编程)中的同一性和相等性之间有什么区别?

What is the difference between identity and equality in OOP (Object Oriented Programming)?

推荐答案

  • identity:一个变量保存着与另一个变量相同的实例.

    相等:两个不同的对象可以可以互换使用.他们经常具有相同的 ID.

    equality: two distinct objects can be used interchangeably. they often have the same id.

    例如:

    Integer a = new Integer(1);
    Integer b = a;
    

    ab 相同.

    在 Java 中,使用 == 测试身份.例如,if( a == b ).

    In Java, identity is tested with ==. For example, if( a == b ).

    Integer c =  new Integer(1);
    Integer d = new Integer(1);
    

    cd 相等但不完全相同.

    c is equal but not identical to d.

    当然,两个相同的变量总是相等的.

    Of course, two identical variables are always equal.

    在 Java 中,相等性由 equals 方法定义.请记住,如果您实现 equals 你还必须实现 hashCode.

    In Java, equality is defined by the equals method. Keep in mind, if you implement equals you must also implement hashCode.

    这篇关于OOP 中的同一性和平等性有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆