

不实现equals方法的情况下比较java list
source link: https://lichuanyang.top/posts/28720/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

不实现equals方法的情况下比较java list
java里比较两个list的值是否一致,不考虑顺序,有多种方法,比如排序后直接用equals比较,相互之间执行两次containsAll等,这些办法都需要我们给list的元素类实现equals和hashcode方法。但是有一种特殊情况,如果我们并不方便去实习类的equals方法,例如是一个古老的第三方jar包,改代码会带来很多未知问题,这时候该怎么办呢。
其实很简单,万能的apache-commons早就想到了这一点,所以在commons-collections4中增加了外部输入equals和hashcode的方法,甚至equals和hashcode方法本身也不需要我们自己写代码,可以用comons-lang包实现,具体代码如下
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
public static <T> boolean isEqualCollection(Collection<T> l1, Collection<T> l2, final String... exludedFields) {
Equator<T> equator = generateEquator(exludedFields);
return CollectionUtils.isEqualCollection(l1, l2, equator);
}
private static <T> Equator<T> generateEquator(final String... exludedFields) {
Equator<T> equator = new Equator<T>() {
@Override
public boolean equate(T o1, T o2) {
if (o1 == null && o2 == null) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.getClass() != o2.getClass()) {
return false;
}
return EqualsBuilder.reflectionEquals(o1, o2, exludedFields);
}
@Override
public int hash(T o) {
return HashCodeBuilder.reflectionHashCode(o, exludedFields);
}
};
return equator;
}
Recommend
-
49
Java 中 hashCode() 和 equals() 的关系是面试中的常考点,如果没有深入思考过两者设计的初衷,这个问题将很难回答。除了应付面试,理解二者的关系更有助于我们写出高质量且准确的代码。 一.基础:hashCode() 和 equals() 简介
-
28
Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated o...
-
12
Java基础之String中equals,声明方式,等大总结 转载请注明出...
-
10
Debugging Java Equals and Hashcode Performance in ProductionHashcode and equals are at the crux of many hard to nail down Java performance issues. Here's how to track it in production.
-
4
本文为博主原创,未经允许不得转载: 1. equals 和 hashCode 方法之间的关系 这两个方法都是 Object 的方法,意味着 若一个对象在没有重写 这两个方法时,都会默认采用 Object 类中的方法实现,它们的关系为: 如果两个对...
-
5
C# 有关List<T>的Contains与Equals方法 【以下内容仅为本人在学习中的所感所想,本人水平有限目...
-
8
A Deep Dive into Java 8 equals() and hashcode()
-
6
【笔记】Java中equals方法的正确使用 2022-10-02 1...
-
8
V2EX › Java Java 里的 equals 方法 lmybill
-
5
Difference between equals method and == operator in java In this post, we can discuss one of the important java interview questions i.e difference between equals() and == operator and sample examples.
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK