문제

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