-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;
    }

}

The above just contains the "settings" I guess for each seat. I'm attempting to call the constructor in a map to pair each unique seat with a seat type (adult/child)/ here is what I came up with:

   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)));

execution of this code out prints "null" to the console. I know I could easily create a new object for each seat but that's not really an option as that would mean I'd have to create 200+ objects.

I wasn't expecting it to work but I was looking for an explanation on why it doesn't and perhaps a possible resolution to the problem.

Thanks in advance!(And sorry, still a beginner).

1 Answers1

1

You need to override the equals and hashCode methods of your Seat class. Try changing your Seat class to the following:

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;
  }
}

This resolves the issue because the hashCode method plays an important role in adding and looking up your value as the key to a HashMap, LinkedHashMap, HashSet, etc. If you override hashCode, you should also override equals, and vice versa.

Take a look at the following questions for more information:

Community
  • 1
  • 1
blacktide
  • 10,654
  • 8
  • 33
  • 53