سؤال

I've been trying to create a class that will model a scenario I've come up with. It will involve a map with string keys and values.

I need to create an instance variable used to reference the map object, and a constructor that creates the empty map and assigns it to the map instance variable.

I've been messing around with map objects but not creating a class using them, and I've hit a mental block!

What's the proper way to actually get a map object?

هل كانت مفيدة؟

المحلول

public class TheClass {    

  private Map<String, String> theMap;

  public TheClass() {
    theMap = new HashMap<>();
  }
}

نصائح أخرى

public class Demo {

    Map<String,String> map = null;

    public Demo()
    {
        map = new HashMap<String,String>();
    }

}

If you want to use HashMap which is Map implementation you can do it like that:

Map<String, String> map = new HashMap<String, String>();

or

Map<String, String> map = new HashMap<>();

in Java 7.

You can also use other implementations like TreeMap.

You can use the HashMap which is an implementation of Map http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Map<String,String> map = new HashMap<String,String>();
map.put("key1", "Value1");
map.put("Key2", "Value2");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top