【问题标题】:Map and HashMap in Java [duplicate]Java中的Map和HashMap [重复]
【发布时间】:2013-02-28 20:56:31
【问题描述】:

我是 java 新手,遇到了 hashmaps 的以下用法:

public static HashMap< String, Integer > Table1;
....
Table1 = new HashMap< String, Integer > ();

.....
public Map<String, Integer> Table2 = new HashMap<String, Integer>();

我的问题是上述陈述是否等效?我看到Map&lt;String, Integer&gt; 用于 Table2。 HashMap&lt; String, Integer &gt; Table1 和 Map&lt;String, Integer&gt; Table2 是相同的编程结构吗?它们可以互换使用吗?

【问题讨论】:

  • code to interface 是一个很好的做法(即你的第二个例子)
  • 一个区别,Table1 是 static。

标签: java map hashmap


【解决方案1】:

Map是一个接口,在HashMap等几种实现中都有实现。

和

HashMap 是一个完整的实现类。

一个有用的答案在这里 -Difference between HashMap and Map in Java..?

【讨论】:

    【解决方案2】:

    Map 是一个接口,HashMap 是它的一个实现。它们只能在一个方向上互换,这意味着在任何可以使用Map 的地方,您都可以使用HashMap。但是,它远不止于此,因为Map 表达了任何类型的“映射”必须提供的所有操作,无论是基于哈希的映射 (HashMap)、排序映射 (TreeMap)、线程- 安全映射 (ConcurrentMap) 或不可变映射 (ImmutableMap from Guava)。任何需要Map 的地方都可以使用这些不同类型的地图等等。 Map 本身不提供任何实际工作代码。它只说明了每种地图必须能够做什么。

    在"Object-Oriented Programming Concepts" 跟踪的"What Is an Interface?" 部分和"Interfaces and Inheritance" 跟踪中的Java 教程中了解有关这种关系的更多信息。

    【讨论】:

      【解决方案3】:

      按照定义,Table1 必须始终是 HashMap,但 Table2 也可以是其他映射。

      public Map<String, Integer> Table2 = new HashMap<String, Integer>();
      Table2 = new TreeMap<String, Integer>();
      Table2 = someFunctionThatReturnsMaps();
      

      最后一个可能是最重要的,因为有多种库会返回 Map 类型,您必须将它们强制转换为 Table1 的 HashMap。

      额外说明:一般约定是变量名以小写开头(table1、table2等)

      【讨论】:

        【解决方案4】:

        Map是接口,HashMap是Map接口的实现类。

        接口变量可以持有子类引用,不能互换使用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-20
          • 2014-05-14
          • 1970-01-01
          • 2012-03-24
          • 2016-04-22
          • 2011-07-05
          • 2014-12-17
          • 2011-08-18
          相关资源
          最近更新 更多