【问题标题】:Return type for Java Hashmap while using wildcards使用通配符时 Java Hashmap 的返回类型
【发布时间】:2013-11-15 21:37:44
【问题描述】:

我有一个名为 Identifier 的类和一些其他名为 Variable、Scalar 等的类,它们都从 Identifier 扩展而来。

所以当我声明一个新的 Hashmap 时:

Hashmap<String, ? extends Identifier> hm = new Hashmap<String, ? extends Identifier>();

当我调用时返回类型是什么:

hm.get(String)

因为显然这样的事情是无效的:

(? extends Identifier) temp = hm.get(String);

如果不进行一些类型转换或使用泛型 Object 作为类型,我真的不知道解决方案,这两者我都不想这样做。

【问题讨论】:

  • 这就是? 的意义所在。你并不确切知道。最多可以是Identifier

标签: java generics hashmap wildcard


【解决方案1】:

你不知道。您所知道的是它的类型为Identifier,这就是您应该对这种情况做出的全部假设。

public Identifier getValue(string value) {
    return hm.get(value);
}

【讨论】:

    【解决方案2】:

    在到达get 之前,您会遇到地图实例化的问题。您不能使用通配符实例化类型:

    //                  Can't do this!
    new Hashmap<String, ? extends Identifier>()
    

    因为您可能不在乎可以存储哪种类型的Identifier,所以只需完全消除通配符即可:

    HashMap<String, Identifier> hm = new HashMap<String, Identifier>();
    

    (这也将允许使用put 方法,没有它以后将不会指向get。)

    Identifier temp = hm.get(someString);
    

    【讨论】:

      【解决方案3】:

      从概念上讲,它几乎是(? extends Identifier)。当然,你不能这样写是对的。但想想这真正意味着什么:“某种类型是Identifier 的子类型”。换句话说:Identifier! (请记住,类型是其自身的子类型)。

      Identifier temp = hm.get(String);
      

      【讨论】:

        猜你喜欢
        • 2011-11-28
        • 2019-03-29
        • 1970-01-01
        • 2016-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        相关资源
        最近更新 更多