等于覆盖String和Int [英] Equals override for String and Int

查看:46
本文介绍了等于覆盖String和Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表中创建了一个对象.通过使用 contains()方法,我想检查对象是否已经存在.为此,我重写了 equals()方法.到目前为止,一切都很完美.但是,当我尝试对 String int 做同样的事情时, equals()覆盖无效.为什么会这样呢?我刚刚发布了一些示例代码以供参考.

I have a list in that list I created an object. By using the contains() method, I want to check whether the object already exists or not. For that, I override the equals() method. Everything is perfect upto this. But when I try to do the same thing for String and int the equals() override doesn't not work. Why is it like this? I just posted some sample code for reference.

public class Test 
{
private int x;

public Test(int n) 
{ 
x = n;
}

public boolean equals(Object o) 
{
return false; 
}

public static void main(String[] args) 
{
List<Test> list = new ArrayList<Test>();
list.add(new Test(3));
System.out.println("Test Contains Object : " + list.contains(new Test(3))); // Prints always false (Equals override)
List<String> list1 = new ArrayList<String>();
list1.add("Testing");
String a = "Testing";
System.out.println("List1 Contains String : " + list1.contains(a)); // Prints true (Equals override not working)
}
}

推荐答案

String和Integer都是最终类,因此您不能对它们进行子类化.因此,您不能覆盖它们的equals方法.

String and Integer are both final classes, so you cannot subclass them. Therefore you cannot override their equals methods.

但是,您可以继承ArrayList的子类,并在现有的基础上创建自己的包含实现.

You can, however, subclass ArrayList and create your own contains implementation builds on the existing one.

这篇关于等于覆盖String和Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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