11行目: | 11行目: | ||
==例== | ==例== | ||
===equalsオーバーライドの定石=== | |||
public boolean equals(Object o) { | |||
if (o == this) return true; | |||
if (o == null) return false; | |||
if(!(o instanceof Account)) return false; | |||
Account act = (Account) o; | |||
if (!this.accountNo.trim().equals(act.accountNo.trim())) { | |||
return false; | |||
} | |||
return true; | |||
} | |||
===hashCodeオーバーライドの定石=== | ===hashCodeオーバーライドの定石=== | ||
class Hero { | class Hero { |
2019年7月2日 (火) 09:12時点における版
私は全てのオブジェクトのスーパークラスです。
メソッド
- hashCode - オブジェクトのハッシュ・コード値を知らせる
- toString - オブジェクトの文字列表現を取得する
- clone - オブジェクトのクローンを作成する
- equals - 引数に指定されたオブジェクトが同じか真偽する
- wait - 実行中のスレッドを一時待機させる
例
equalsオーバーライドの定石
public boolean equals(Object o) { if (o == this) return true; if (o == null) return false; if(!(o instanceof Account)) return false; Account act = (Account) o; if (!this.accountNo.trim().equals(act.accountNo.trim())) { return false; } return true; }
hashCodeオーバーライドの定石
class Hero { String name; int hp; public int hashCode() { int result = 37; result = result * 31 + name.hashCode(); 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; } }