gpt4 book ai didi

java - 我试图获取集合中的最后一个日期元素,但是它一直返回第一个日期元素?

转载 作者:行者123 更新时间:2023-12-02 10:42:01 24 4
gpt4 key购买 nike

下面是我的代码,我获取 map 的键,然后迭代它们以获取最后日期,但是它似乎没有获取最后日期。该行的值Set<Date> keys = date.keySet();分别是 2018 年 10 月 31 日和 2018 年 17 月 11 日。我希望 lastDate 等于 11.17.18,但它等于 10.31.18。任何想法我在这里做错了什么。

Map<Date, List<Integer>> date = date(dates, noPupils);
Set<Date> keys = date.keySet();
for (Iterator<Date> it = keys.iterator(); it.hasNext();) {
while (it.hasNext()) {
Date lastDate = it.next();

最佳答案

看来您遵循了此answer 。它已经说:

A Collection is not a necessarily ordered set

在你的情况下它不起作用 because

The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

显然是 Map date不保证特定顺序。这也适用于Set<Date> keys = date.keySet() as this

Returns a Set view of the keys contained in this map ... is backed by the map ...

但是解决方案很简单并且开箱即用:

Date lastDate = Collections.max(keys);

这会立即起作用,因为 Date实现Comparable .

关于java - 我试图获取集合中的最后一个日期元素,但是它一直返回第一个日期元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52860048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com