Search code examples
javahashmapkeytostring

Hash map key weird key order


I am doing a HashMap that uses dates as key and assigns them a pet obeject (pet of the month). Pet holds a bunch of values like name, age, type... (not relevant) and has a method that generates one randomly. It goes soemthing like this:

DateTimeFormatter date_format = DateTimeFormatter.ofPattern ("dd/MM/yyyy");
LocalDate date = LocalDate.of(2023, 1, 1);
HashMap<LocalDate, Pet> pets = new HashMap<>();

//* This next chunk generates a random pet (that has not yet been chosen) and makes it the pet of the month using the date as the key and the pet as the value

for (int i=0; i < 12; i++){
            Pet pet_of_the_month = Pet.randompet(); 
            if (!pets.containsValue(pet_of_the_month)){ 
                pets.put(date, pet_of_the_month); 
                date = date.plusMonths(1);
            } else {
                i--;
            }
        }

//*This loops around the map taking every key and printing both the key (date) and the object (pet)

for (LocalDate month: pets.keySet()) {
            System.out.println("Date of" + month.format(date.format) + ":" + pets.get(month).toString());
        }

The issue I have is that this for some reason ALWAYS prints the month 4 first and then the rest in order (4,1,2,3,5,6...); is there a reason for why it is doing that?;am I doing something wrong/missing something or is just some random interaction that I have to assume?


Solution

  • Maps are unordered due to the hashCode used to determine in which "bucket" the entry is to be placed. If you want to preserve the insertion order, you can use a LinkedHashMap in place of HashMap. If you want to ensure the keys (here LocalDate) are sorted (LocalDate implements Comparable) you can use a TreeMap