Java 如何创建地图实例变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22325185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:57:01  来源:igfitidea点击:

How to create a map instance variable

javamapbluej

提问by Harry Jones

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?

实际获取地图对象的正确方法是什么?

采纳答案by rogue-one

public class TheClass {    

  private Map<String, String> theMap;

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

回答by rogue-one

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

您可以使用 HashMap,它是 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");

回答by Jakub H

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

如果你想使用 HashMap 这是 Map 实现,你可以这样做:

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

or

或者

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

in Java 7.

在 Java 7 中。

You can also use other implementations like TreeMap.

您还可以使用其他实现,例如 TreeMap。

回答by Kick

public class Demo {

    Map<String,String> map = null;

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

}