这些初始化 HashMap 的方式有什么区别? [英] What's the difference between these ways of initializing a HashMap?

查看:28
本文介绍了这些初始化 HashMap 的方式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中使用了一个 HashMap,它工作正常,但我不明白这些 HashMap 初始化之间的区别.

假设我正在实现一个 HashMap,其中一个字符作为键,一个整数作为值.这些有什么区别?

HashMap<字符,整数>字母 1 = 新的 HashMap();HashMap<字符,整数>字母 1 = 新的 HashMap<字符,整数>();HashMap 字母1 = new HashMap<字符,整数>();映射字母1 = new HashMap<字符,整数>();HashMap 字母1 = new HashMap<字符,整数>();HashMap 字母 1 = new HashMap();地图字母1 = new HashMap();

解决方案

任何涉及 HashMapMap 没有类型参数(尖括号 < 和 >它们之间的部分)是 原始类型和不应该使用.原始类型不是通用的,它会让你做不安全的事情.

正确"的方法是

Map<字符,整数>字母 1 = 新的 HashMap<字符,整数>();HashMap<字符,整数>字母 1 = 新的 HashMap<字符,整数>();

第一个使用接口 Map 作为引用类型.它通常更惯用,风格也很好.p>

还有另一种你没有提到的方式,使用 Java 7 菱形运算符

Map<字符,整数>字母 1 = 新的 HashMap<>();HashMap<字符,整数>字母 1 = 新的 HashMap<>();

这或多或少等同于前两种正确方法.左侧引用类型的参数隐式提供给右侧的构造函数.

I used a HashMap for my program and it works fine, but I don't understand the difference between these initializations of HashMap.

Let's say I'm implementing a HashMap with a character as a key and an integer as a value. What's the difference between these?

HashMap<Character, Integer> alphabet1 = new HashMap();
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap<Character, Integer>();
Map alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap();
Map alphabet1 = new HashMap();

解决方案

Anything involving HashMap or Map without a type argument (the angle brackets < and > and the part between them) is a raw type and shouldn't be used. A raw type is not generic and lets you do unsafe things.

The "correct" ways are

Map<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>();

The first uses the interface Map as the reference type. It is generally more idiomatic and a good style.

Also another way you did not mention, using the Java 7 diamond operator

Map<Character, Integer> alphabet1 = new HashMap<>();
HashMap<Character, Integer> alphabet1 = new HashMap<>();

Which is more or less equivalent to the first two correct ways. The arguments to the reference type on the left-hand side are supplied implicitly to the constructor on the right-hand side.

这篇关于这些初始化 HashMap 的方式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆