如何在实现内容相等的对象中检查引用相等? [英] how to check reference equality in an object which implements content equality?

查看:91
本文介绍了如何在实现内容相等的对象中检查引用相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

...换句话说: 假设我有2个这样声明的字符串:

...in other words: let's suppose I have 2 Strings declared as so:

String one = new String("yay!");
String two = new String("yay!");

这两个字符串是两个不同的对象,但是如果我运行

these two Strings are two different objects, but if I run

if(one.equals(two))
   System.out.println("equals() returns true.");

我得到"equals()返回true". 这是因为String类重写equals()方法以实现内容级别相等. 但是,我需要访问一个引用级别的相等性(例如在Object中实现的相等性),以将一个对象与两个对象区分开. 我该怎么办?

I get "equals() returns true". This is because the String class overrides the equals() method to implement a content level equality. However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two. How can I do that?

我尝试过:

one.getClass().getSuperclass().equals();

尝试调用一个String的Object equals()方法,但是没有用.

to try to invoke the Object equals() method of the String one but it didn't work.

有什么建议吗?

推荐答案

String在Java中使用String Literal Pool,这意味着:当您尝试构造字符串时,首先在Literal Pool中搜索传统的字符串类相同的字符串,如果存在则返回它,如果不存在则创建它",因此您无法通过equals方法检查String实例的引用是否匹配,您必须使用==运算符,如下所示:

String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:

String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
   System.out.println("equals() returns true.");
if(one == two)
   System.out.println(" == operator returns true.");

结果是:

equals() returns true.

有关更多信息,请参见以下链接:

see following link for more information:

  1. http://blog.enrii. com/2006/03/15/java-string-equality-common-mistake/
  2. Java String.equals与==
  1. http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
  2. Java String.equals versus ==

这篇关于如何在实现内容相等的对象中检查引用相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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