[英]How to check whether two objects have the same values in Java?
I have two objects of the same class. 我有两个相同类的对象。 The class is containing so many other objects with different types like List<>, ...
该类包含许多其他类型不同的对象,例如List <>,...
What is the best way to determine if this two have the same values? 确定这两个值是否相同的最佳方法是什么? I'm trying to use hashcode function but it doesn't seem to work for me.
我正在尝试使用哈希码功能,但它似乎对我不起作用。
public class MyClass{
List<OtherClass> myList;
String foo;
SubClass mySubClass;
public MyClass(values...){ ... }
...
}
MyClass obj1 = new MyClass(values...);
MyClass obj2 = new MyClass(values...); // same values with obj1
if(obj1.hashcode() == obj2.hashcode()){
System.out.println("This is what I want");
}else{
System.out.println("This is what happens");
}
You need to override the equals() and hashcode() methods of MyClass. 您需要重写MyClass的equals()和hashcode()方法。
Your ide can probably do it for you. 您的助手可能会为您做到这一点。
What you want is a deep compare. 您想要的是深入比较。 The equals method should go into each list and iterate, and compare.
equals方法应进入每个列表并进行迭代和比较。
hashcode should use the hashcode of each element to to generate a hashcode. 哈希码应使用每个元素的哈希码来生成哈希码。
Please override the equals method to check for equality. 请重写equals方法以检查是否相等。 Do not use the hashcode for equality checking.
不要将哈希码用于相等性检查。
Please check the java documentation on equals/hashcode, as it is probably too verbose for this post to put the diff. 请检查有关equals / hashcode的Java文档,因为这篇文章可能太冗长,无法放入diff。 between equals/hashcode and its uses.
在equals / hashcode及其用法之间。
In order to compare two Lists, you could simply use the list.equals method... no need to iterate the lists for Ex (Please see java.util.List documentation for equals) ; 为了比较两个列表,您可以简单地使用list.equals方法...无需为Ex迭代列表(请参见java.util.List文档中的equals);
// Sample Code...
public class MyClass {
List<OtherClass> myList;
public boolean equals(Object o) {
if (o instanceof List) {
myList.equals((List) o) ;
}
return false;
}
}
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.