java Map 的 size() 方法返回什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7425131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:55:27  来源:igfitidea点击:

What does Map's size() method return?

javamapsize

提问by Bhesh Gurung

I have a map declared as follows -

我有一张地图声明如下 -

Map<Date, Long[]> myMap = new TreeMap<Date, Long[]>();

I put some key-value pairs in that map, check the size as follows -

我在那个映射中放了一些键值对,检查大小如下 -

myMap.size(); //returns 29

myMap.values().size(); //returns 31

All the dates (keys) are distinct.

所有日期(键)都是不同的。

Aren't those two supposed to return same values?

这两个不应该返回相同的值吗?

回答by Ryan Stewart

Given that the collection returned by TreeMap's values() method (in JDK 6, at least) has a size as follows:

鉴于 TreeMap 的 values() 方法(至少在 JDK 6 中)返回的集合的大小如下:

public int size() {
    return TreeMap.this.size();
}

I'd say you have something adding new entries to the map between your two size()calls. To be clear, map.values().size()delegates to map.size(). Therefore there's no way they can return two different values for the same map with the same contents.

我会说你有一些东西在你的两次size()调用之间向地图添加新条目。明确地说,map.values().size()委托给map.size(). 因此,他们无法为具有相同内容的同一地图返回两个不同的值。