简体   繁体   English

HashMap K和V的默认类型

[英]HashMap default types for K and V

I usually type my map declarations but was doing some maint and found one without typing. 我通常键入我的地图声明,但是正在做一些maint并找到一个没有输入。 This got me thinking (Oh No!). 这让我想到了(哦不!)。 What is the default typing of a Map declaration. Map声明的默认输入是什么。 Consider the following: 考虑以下:

Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Map.Entry entry : map.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

this errors with a incompatible types on Map.Entry. Map.Entry上的类型不兼容时出现此错误。 So if I type the declaration with: 所以,如果我输入声明:

Map<Object, Object> map = new HashMap();

then all works well. 一切顺利。 So what is the default type that gets set in the declaration about? 那么在声明中设置的默认类型是什么? Or am I missing something else? 还是我错过了别的什么?

There is no default type. 没有默认类型。

The types in Java generics are only for compile-time checking. Java泛型中的类型仅用于编译时检查。 They are erased at runtime and essentially gone. 它们在运行时被删除,基本消失了。

Think of generics as a static helper to a) better document your code, and b) enable some limited compile-time checking for type safety. 将泛型视为静态帮助程序,以便a)更好地记录代码,以及b)为类型安全启用一些有限的编译时检查。

The type is java.lang.Object . 类型是java.lang.Object

The for construct takes a type of Iterable and calls its iterator method. for构造采用Iterable类型并调用其迭代器方法。 Since the Set isn't typed with generics, the iterator returns objects of type Object . 由于Set没有使用泛型类型,因此迭代器返回Object类型的对象 These need to be explicitly cast to type Map.Entry . 这些需要显式转换为Map.Entry类型。

Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Object o : map.entrySet()) {
    Map.Entry entry = (Map.Entry) o;
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

HashMap is a collection of objects, Think C++ containers. HashMap是一组对象,即Think C ++容器。 Each element of the map is a "bucket" to hold data. 地图的每个元素都是一个用于保存数据的“存储桶”。
You are putting different types of data in the buckets, the hashmap needs to know that these are not all the same data type. 您在桶中放置了不同类型的数据,hashmap需要知道这些数据类型并不完全相同。 If only one type of data was placed in the hashmap, you would get a warning but it would compile. 如果在hashmap中只放置了一种类型的数据,则会收到警告,但会进行编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM