2016-04-06 7 views
-3
//Represents a seat on a plane. 
public class Seat { 

    //The section that the seat is in. 
    public int sectionId; 
    public int seatId; 

    public Seat(int seatId, int sectionId) { 
     this.seatId = seatId; 
     this.sectionId = sectionId; 
    } 

} 

上記には、各座席の「設定」が含まれています。うち、このコード版画「ヌル」のハッシュマップのキーとしてのコンストラクタ?

public enum SeatType { 
    ADULT, 
    CHILD; 
} 

private static Map<Seat, SeatType> map = new LinkedHashMap<>(); 

public static void main(String[] args) { 
    int sectionId = 5; 
    map.put(new Seat(1, 5), SeatType.ADULT); 
    System.out.println(map.get(new Seat(1, 5))); 

実行:私はシートタイプ(大人/子供)と、それぞれ独自の席をペアリングするマップでコンストラクタを呼び出そうとしています/ここに私が思い付いたものですコンソールに接続します。私は簡単に各座席のための新しいオブジェクトを作成することができますが、それは本当に私は200以上のオブジェクトを作成する必要があることを意味するオプションはありません。

私はそれがうまくいくとは思っていませんでしたが、なぜそうではないのか、おそらく問題の解決方法を探していました。

ありがとうございます。(ごめんなさい、まだ初心者です)。

答えて

1

SeatクラスのequalshashCodeメソッドをオーバーライドする必要があります。以下に、あなたのSeatクラスを変更してみてください:これで問題が解決

public class Seat { 

    public int sectionId; 
    public int seatId; 

    public Seat(int seatId, int sectionId) { 
    this.seatId = seatId; 
    this.sectionId = sectionId; 
    } 

    @Override 
    public boolean equals(Object o) { 
    if (this == o) return true; 
    if (o == null || getClass() != o.getClass()) return false; 

    Seat seat = (Seat) o; 
    if (sectionId != seat.sectionId) return false; 
    return seatId == seat.seatId; 
    } 

    @Override 
    public int hashCode() { 
    int result = sectionId; 
    result = 31 * result + seatId; 
    return result; 
    } 
} 

hashCode方法は、あなたの場合などHashMapLinkedHashMapHashSetにキーとしてあなたの価値を追加して検索するのに重要な役割を果たしているので、 hashCodeを上書きする場合は、equalsも上書きする必要があります。逆の場合も同様です。

詳細については、次の質問を見てみましょう:

関連する問題