我正在做一个HashMap,它使用日期作为键,并为他们分配一个宠物服从对象(每月的宠物).宠物有一堆价值观,比如名字、年龄、类型……(不相关),并且有一个随机生成一个的方法.事情大概是这样的:
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());
}
我的问题是,由于某种原因,它总是先打印月份4,然后按顺序打印其余月份(4,1,2,3,5,6...);它这样做有什么原因吗?我是做错了什么/错过了什么,还是我必须假设的某种随机交互?