我正在做一个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...);它这样做有什么原因吗?我是做错了什么/错过了什么,还是我必须假设的某种随机交互?

推荐答案

映射是无序的,因为hashCode用于确定条目将被放置在哪个"桶"中.如果要保留插入顺序,可以使用LinkedHashMap代替HashMap.如果您想确保密钥(这里是LocalDate)是排序的(LocalDate实现Comparable),您可以使用TreeMap

Java相关问答推荐

'在使用apache poi生成Excel数据透视表时,行标签显示为第一列标题,并显示分类汇总

Android -如何修复Java.time.zone. ZoneRulesExcept:未知时区ID:Europe/Kyiv

Java应用程序崩溃时试图读取联系人从电话

@ IdClass with @ Inheritance(策略= InheritanceType. SINGLE_TABLE)

这是什么Java构造`(InputStream Is)->;()->;{}`

自定义批注的外推属性值

如何从Keyloak映射Hibernate实体中的用户

对字符串长度进行排序,但颠倒了顺序(最长字符串在前)

使用存储在字符串变量中的路径目录打开.pdf文件

如何从日志(log)行中删除包名称?

在执行流和相关操作时,使用Java泛型为2个方法执行相同的操作,但对象不同

Java中不兼容的泛型类型

根本不显示JavaFX阿拉伯字母

为什么我不能建立输入/输出流?Java ServerSocket

Java嵌套流查找任意值

活泼的一次判断成语,结果中等

使用@ExceptionHandler的GlobalExceptionHandler还是来自服务器的REST应答的ResponseEntity?

如何使用Rascal Evaluator从编译的JAR访问Rascal函数?

org.springframework.web.HttpRequestMethodNotSupportedException:请求方法';帖子';不支持

如何使用外部函数从Java中获取C++ struct 的返回值&;内存API