【发布时间】:2015-03-19 07:56:46
【问题描述】:
我在将 HashMap A 复制到 HashMap B 时遇到问题。B 始终与 A 相同。我的想法是仅使用 HashMaps 制作一个小型拼图游戏。
Map<Point,Tile> A = new HashMap<Point,Tile>();
HashMap 有两件事。一个点(键)和一个瓦片对象,这是我制作的另一个类。 Tile 接受两个整数和一个字符串。 (新平铺(x,y,字符串))。前两个整数定义点 x 和 y,字符串告诉它是“OFF”还是“ON”。
我首先要做的是用 2*2 个元素填充 HashMap A。
for(int i=0; i<2;i++){
for(int j=0; j<2;j++){
Tile t = new Tile(i, j, "OFF");
A.put(new Point(i,j), t);
}
}
然后我通过在构造函数中添加 A 来将 HashMap A 复制到 HashMap B。我的想法是,我可以通过在构造函数中使用 HashMap B 回到默认的 HashMap A(见后文)
Map<Point,Tile> B = new HashMap<Point,Tile>(A);
然后我将图块 (1,1) 更改为“ON”
Tile t2 = A.get(new Point(1,1));
t2.setS("ON");
我的一个图块现在是“开启”的。现在我想将板重置为原始状态(在人口阶段之后)。我清除 HashMap A 并使用 HashMap B 作为构造函数创建一个新的 HashMap。
A.clear();
A = new HashMap<Point,Tile>(B);
但是,当我在 HashMap A 上将 tile (1,1) 更改为 ON 时,它也更新了 HashMap B。我认为使用构造函数创建一个新的 HashMap 会创建一个新副本,但似乎不起作用。
奇怪的是
Map<Point,String> A = new HashMap<Point,String>();
可以,但不行
Map<Point,Tile> A = new HashMap<Point,Tile>();
我想以某种方式获取 HashMap A 的原始内容,而无需再次尝试遍历元素。
这是我的主要课程代码
package main;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import model.Tile;
public class Test {
public static void main(String[] args) {
//list1
Map<Point,Tile> A = new HashMap<Point,Tile>();
//Populating map
for(int i=0; i<2;i++){
for(int j=0; j<2;j++){
Tile t = new Tile(i, j, "OFF");
A.put(new Point(i,j), t);
}
}
//copying list1 to list2
Map<Point,Tile> B = new HashMap<Point,Tile>(A);
//Change tile on 1,1 to ON
Tile t2 = A.get(new Point(1,1));
t2.setS("ON");
for(int i=0; i<2;i++){
for(int j=0; j<2;j++){
Tile tTemp = A.get(new Point(i,j));
System.out.println(i+" "+j+" "+tTemp.getS());
}
}
//Reseting tiles
//clear first list
A.clear();
System.out.println("");
//copy second list to first list
A = new HashMap<Point,Tile>(B);
for(int i=0; i<2;i++){
for(int j=0; j<2;j++){
Tile tTemp = A.get(new Point(i,j));
System.out.println(i+" "+j+" "+tTemp.getS());
}
}
}
}
这是瓦片类
package main;
public class Tile {
public int x,y;
public String s;
public Tile(int x1, int y1, String st){
x=x1;
y=y1;
s=st;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
这是在清除 HashMap A 之前打印的内容
0 0 OFF
0 1 OFF
1 0 OFF
1 1 ON
这是在清除 HashMap A 然后将 B 复制到它之后打印的内容。
0 0 OFF
0 1 OFF
1 0 OFF
1 1 ON
没有区别。
【问题讨论】:
标签: java dictionary hashmap copy