| 30行目: | 30行目: | ||
public int hashCode() { | public int hashCode() { | ||
int result = 37; // 0以外ならなんでも良い | int result = 37; // 0以外ならなんでも良い | ||
result = result * 31 + name.hashCode(); | result = result * 31 + name.hashCode(); // 31:奇数かつ素数 | ||
result = result * 31 + hp.hashCode(); | result = result * 31 + hp.hashCode(); | ||
return result; | return result; | ||
2019年7月2日 (火) 09:30時点における版
私は全てのオブジェクトのスーパークラスです。
メソッド
- hashCode - オブジェクトのハッシュ・コード値を知らせる
- toString - オブジェクトの文字列表現を取得する
- clone - オブジェクトのクローンを作成する
- equals - 引数に指定されたオブジェクトが同じか真偽する
- wait - 実行中のスレッドを一時待機させる
例
equalsオーバーライドの定石
public boolean equals(Object o) {
if (o == this) return true;
if (o == null) return false;
if(!(o instanceof Monster)) return false;
Monster mon = (Monster) o;
if (!this.fieldName.trim().equals(mon.fieldName.trim())) {
return false;
}
return true;
}
hashCodeオーバーライドの定石
class Hero {
String name;
int hp;
public int hashCode() {
int result = 37; // 0以外ならなんでも良い
result = result * 31 + name.hashCode(); // 31:奇数かつ素数
result = result * 31 + hp.hashCode();
return result;
}
}
clone実装の例
Object自身はインタフェースCloneableを実装していないため、クラスで実装する必要がある。
public class Hero implements Clonable {
String name;
int hp;
Sword sword;
public Hero clone() {
Hero result = new Hero();
result.name = this.name;
result.hp = this.hp;
result.sword = this.sword; // shallow copy
// result.sword = this.sword.clone(); // deep copy
return result;
}
}