0
0

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 1 year has passed since last update.

Java オーバーライドするメソッド・インスタンスの順序づけ

Last updated at Posted at 2022-09-22

Java 1日目

equals/toString/hashCodeのオーバーライドが大事

toString method
  public String toString(){
        return "勇者(名前"+this.name+")/HP="+this.hp;
    }

equal method
public boolean equals(Object o){
        if(o==this)return true;
        if(o==null)return false;
        if(!(o instanceof Hero)) return false;
        Hero hs=(Hero)o;
        if(!this.name.trim().equals(hs.name.trim())){
            return false;
        }
        return true;
}

なお、apacheのライブラリをつかうとequalsはこのようにも書き直せる

import org.apache.commons.lang3.builder.*;
//省略
public boolean equals(Object o){
    return EqualsBuilder.reflectionEquals(this,o);
//全てのフィールドが等価であるかどうかを調べる
}
hashCode method
public int hashCode(){
    return object.hash(this.name,this.hp);
}

インスタンスの順序づけ
自然順序づけを宣言するために
java.lang.Comparableインタフェースを実装する。

Comprable
public class Book implements Comparable<Book>,Cloneable {
    private String title;
    private Date publishDate;
    private String comment;

public int compareTo(Book o) {
        return this.publishDate.compareTo(o.publishDate); 
    }
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?