如何在工厂方法中为Hashmap <String Boolean>创建构造函数?

代码Newb:

我在公共类中为Hashmap创建工厂方法。

 public class MyList {
    Hashmap list = newMap();   //is this function called properly here?

public static final Hashmap newMap() {
    return Hashmap(String, boolean);

  }
 }

以最简单的方式,如果要为键/值对保留字符串和布尔值,如何设置工厂方法?

我陷入语法。

我只想返回一个新的Hashmap对象,并使用newMap()作为工厂方法

Azro:
  1. HashMap 具有键和值的通用类型,因此您需要将这些类型指定为

    public static HashMap<String, Boolean> newMap() {
        // ...
    }
    
  2. 在内部,您将创建地图为

    • return new HashMap<String, Boolean>();
    • 或就像return new HashMap<>();使用菱形运算符一样(因为签名中已经有类型
  3. 您也可以将类型作为参数传递

    public static <K, V> HashMap<K, V> newMap(Class<K> classKey, Class<V> classValue) {
        return new HashMap<>();
    }
    

public static void main(String[] args) {
    Map<String, Boolean> map = newMap();
    Map<Integer, Double> mapID = newMap(Integer.class, Double.class);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章