[英]What is the fastest and efficient way to check Deep Equal for two java objects?
I have got two java objects with byte[]
field of the size of the order of millions . 我有两个java对象,其
byte[]
字段的大小为数百万 。 What is the fastest and efficient way to check Deep Equal for these java objects? 检查这些java对象的Deep Equal的最快捷有效的方法是什么?
Sample Entity: 样本实体:
@Entity
public class NormalBook
{
@Id
private String bookId;
@Column
private String title;
@Column
private byte[] pdfFile;
//setters and getters
}
Note: I am doing it for an ORM tool basically I am checking an object ( which is in managed state ) with an object present in Persistence Context.
注意:我正在为ORM工具执行此操作,基本上我正在使用Persistence Context中存在的对象检查对象( 处于托管状态 )。
Override equals()
or have a *helper method (bad option!) and do it in 5 steps : 覆盖
equals()
或者有一个* helper方法(错误选项!)并分五步完成:
1. Check for *not null*.
2. Check for same *type*.
3. Check for *size of byte[]*.
4. Check for `==` (*reference equality* of byte[])
5. Start comparing byte values
Use the following in the definition of equals()
on your object's class: 在对象类的
equals()
定义中使用以下内容:
java.util.Arrays.equals(bs1, bs2)
You might also want to check if they are the same array (instance) first. 您可能还想先检查它们是否是相同的数组(实例)。 Though this method may well do that anyway.
虽然这种方法无论如何都可能做到这一点。
For example (and making some assumptions about your class that contains the arrays): 例如(并对包含数组的类做出一些假设):
public boolean equals(Object obj) {
if(this == obj)
return true;
if(!(obj instanceof MyObject)) // covers case where obj null, too.
return false;
return Arrays.equals(this.bytes, ((MyObject)obj).bytes);
}
If there are other fields in your class, your equals()
should take those into account too. 如果您的班级中还有其他字段,则您的
equals()
应考虑这些字段。
(There might be a better answer to the question if you could provide more information about what kind of data is stored in the arrays.) (如果您可以提供有关阵列中存储的数据类型的更多信息,则可能有更好的答案。)
if your class have fields like byte[]
you can use something like: 如果你的类有像
byte[]
这样的字段你可以使用类似的东西:
public class MyClass {
byte[] a;
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyClass other = (MyClass) obj;
if (!Arrays.equals(a, other.a))
return false;
return true;
}
}
If you are concern about performance and can assure a unique hascode
(this is important hascode
need to be unique
) then you can just compare the hascode. 如果您关注性能并且可以确保唯一的
hascode
(这是重要的hascode
必须是unique
),那么您可以只比较hascode。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.