等于覆盖 String 和 Int
我在该列表中有一个列表,我创建了一个对象。通过使用 contains()
方法,我想检查该对象是否已经存在。为此,我重写了 equals() 方法。至此一切都很完美。但是,当我尝试对 String
和 int
执行相同的操作时,equals()
覆盖不起作用。为什么会这样呢?我刚刚发布了一些示例代码以供参考。
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)
}
}
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)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
String 和 Integer 都是最终类,因此不能对它们进行子类化。因此您不能重写它们的 equals 方法。
但是,您可以继承 ArrayList 并在现有实现的基础上创建自己的 contains 实现。
String and Integer are both final classes, so you cannot subclass them. Therefore you cannot override their equals methods.
You can, however, subclass ArrayList and create your own contains implementation builds on the existing one.
无需重写 Integer 或 String 的 equals 方法,因为它们已经实现并且运行良好。
但是,如果您无论如何都想这样做,这将是一种方法(委托模式):
当然,那么你必须使用这个类,而不是列表中的 String 类。
There is no need for overriding the equals method of Integer or String as they are already implemented and work well.
However, if you want to do it anyways, this would be one way of doing it (Delegation Pattern):
Of course, then you must be using this class, not the String class in your lists.
关于蒂姆的回答,您可以执行以下操作:
输出为
true
。Regarding Tim's answer you can do something like this:
The output is
true
.