如何声明和初始化包含哈希集的哈希图



我正在尝试读取包含字符串作为键的映射,而集合作为值,我该如何处理?这就是我得到的。

/**
 * A Class
 */
public class Catalog
{  
   private HashMap <String , Set<String> varieties> aCatalog;
   /**
    * Constructor for objects of class Catalog
    */
   public Catalog()
   {
      // initialise instance variables
      varieties = new HashSet<>();
      aCatalog = new HashMap<String,varieties>();
   }
}

这不起作用,我查看了一些类似的问题,但找不到解决方案。

感谢您的帮助!

要初始化地图,您只需要定义通用类型:

aCatalog = new HashMap<String, Set<String>>();

由于Java 1.7您可以使用钻石操作员:

aCatalog = new HashMap<>();

要将值放入您的地图中,您需要初始化一个集合:

aCatalog.put("theKey", varieties);

您可以做:

    // declare:
    Map<String, Set<String>> aCatalog;
    // init java 7
    aCatalog = new HashMap<>();
    // insert:
    aCatalog.put("AA", new HashSet<>());

或在较旧版本中:

    // declare:
    Map<String, Set<String>> aCatalog;
    // init java  
    aCatalog = new HashMap<String, Set<String>>();
    // insert:
    aCatalog.put("AA", new HashSet<String>());

不要自己做,您想要的是Google Guava的美丽多胶片。要初始化您可以这样使用构建器:

SetMultimap<String, String> yourMap = MultimapBuilder.hashKeys()
         .linkedHashSetValues().build();

希望它有帮助!

okey,您对变量的类型有问题,并且您正在混淆如何初始化对象,这是两种做到的方法:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Catalog {
    //is better to use interface for the type of the variable
    private Map<String, Set<String>> aCatalog;
    // here in your constructor, you just initialize an empty Hash, the most
    // external one
    public Catalog() {
        aCatalog = new HashMap<String, Set<String>>();
        // aCatalog = new HashMap<>(); //this is also valid since 1.7
    }
    //you can also create another constructor, and create the map outside and give it as parameter
    public Catalog(Map<String, Set<String>> catalog) {
        this.aCatalog = catalog;
    }

    public Map<String, Set<String>> getaCatalog() {
        return aCatalog;
    }

    public static void main(String[] args) {
        //here is an example of creating the map inside the Catalog class
        Catalog catalog1 = new Catalog();
        String key1 = "k1";
        Set<String> valueSet1 = new HashSet<String>();
        valueSet1.add("something 1");
        valueSet1.add("something 2");
        valueSet1.add("something 3");
        String key2 = "k2";
        Set<String> valueSet2 = new HashSet<String>();
        valueSet2.add("other thing1");
        valueSet2.add("other thing2");
        valueSet2.add("other thing3");
        catalog1.getaCatalog().put(key1, valueSet1);
        catalog1.getaCatalog().put(key2, valueSet2);
        //and here is an example of givin as constructor parameter
        Map<String, Set<String>> anotherCatalog = new HashMap<>();
        anotherCatalog.put(key1, valueSet2);
        anotherCatalog.put(key2, valueSet1);
        Catalog catalog2 = new Catalog(anotherCatalog);

    }
}

最新更新