0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[java]独自クラスのListを比較するときにやったこと

Posted at

equalsメソッドとhashCodeメソッドを追加すればよさそうだったので、org.apache.commonsのライブラリを使ったら短くできました。

Hoge.java
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
~~省略~~
    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
 
    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

gradle使ってるなら下記記載。

build.gradle
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'

古い記事ばっかだったのでほかも調べたら下記みたいな事でも実現できそうでした。
※試してはいないです

Hoge.java
@Override
public int hashCode(){
    return Objects.hash(name, length, children);
}

@Override
public boolean equals(final Object obj){
    if(obj instanceof Bean){
        final Bean other = (Bean) obj;
        return Objects.equals(name, other.name)
            && length == other.length // special handling for primitives
            && Objects.equals(children, other.children);
    } else{
        return false;
    }
}

Objectsはnullチェックでお世話になっていましたが、こんなメソッドもあるのは知らなかったです。

Eclipseの自動生成でもできた気がしますが、個人的には動けばそっちでもいいと思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?