How to have a HashMap with different types as values

Question from FellowTomato#4643:

public static HashMap<String, Integer> seats = new HashMap<>(){{
       put("total_rows", 9);
       put("total_columns", 9);
       put("available_seats", new HashMap<String, Integer>(){{
           put("row", 1);
           put("column", 1);   }});
  }};

How should I initialize HashMap to allow several datatypes as values?

I want something like this in result:

{
  "total_rows":5,
  "total_columns":6,
  "available_seats":[
     {
        "row":1,
        "column":1
     },
...];

Turns out, I can simply type Object...

You usually want to make objects for parsing json, not Map<Object,Object>

Sorry, I'm really new to Java. Can you provide an example?

Okay so for what you have there

      {
         "row":1,
         "column":1
      },

when we put this into Java we want to map it to a class like so

public record SeatPosition(int row, int column) {}

and then for the whole structure

public record Theater(int totalRows, int totalColumns, List<SeatPosition> availableSeats) {}

Ah, you mean make a special class for a second HashMap?

Only use a hash map if every key maps to the same thing and you don't know the set of keys ahead of time.

If you know the set of things "total_rows", "available_seats" - that is your clue you should be representing things as classes.

records are a good default for this kind of thing. They are just a shorthand way of making a class that contains data and has methods for accessing it.


<- Index