Posts Tagged ‘Remove’
HashMap中以动态对象作为Key值时的Remove陷阱
星期一, 十一月 5th, 2012 141 views在游戏服务器上控制角色的坐标点可以通过Point这个类来实现,地图模块则以HashMap来承载。此问题从简单来说,既HashMap以Point作为Key值时,用户往往会忽略其中一个细节照成后期的非编译Bug。
以下是示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | HashMap <point ,String] hashMap = new HashMap<Point, String]();//把]换成> Point A = new Point(2,2); hashMap.put(A,"A");//将2,2点作为Key值存入HashMap A.x = 1;//修改A点的x值 A.y = 1;//修改A点的y值 System.out.println(hashMap.get(A));//此时结果为Null 已经找不到了 //我们试着迭代一下 System.out.println(hashMap.size());//此处为1 for(Iterator<string ] iterator = hashMap.values().iterator();iterator.hasNext();) { iterator.next(); iterator.remove(); } System.out.println(hashMap.size());//此处依旧为1 即无法销毁 |