如何将内容从以前的hashmap传输到新的hashmap?

Thi*_*Guy 1 java hashmap

  HashMap<String,Integer> map= new HashMap<String,Integer>();
  map.put("first",1);
  map.put("second",2);
  map.put("third",3);

  HashMap<String,Integer> map2= new HashMap<String,Integer>();
  map2= map.clone();
Run Code Online (Sandbox Code Playgroud)

我的问题是如何将项目从地图转移到map2?我的代码是对的吗?

Alg*_*ist 7

它很简单.使用参数化构造函数

  HashMap<String,Integer> map2= new HashMap<String,Integer>(map);
Run Code Online (Sandbox Code Playgroud)

  • 在一个完美的世界中,Map <String,Integer> map2 = ...` - 最好尽可能使用接口. (2认同)