`
cloudeagle_bupt
  • 浏览: 541233 次
文章分类
社区版块
存档分类
最新评论

关于HashMap的使用问题

 
阅读更多
/**
* 常规思路:求两个无向图邻接表交集,前一种方法过于复杂.不对顶点序号做出改变,直接混合两个邻接表,然后执行相对的顶点序号修改,
* 同样能够保持两个文件顶点一一对应的关系,
* 但是新增顶点就会散布在新生成的混合文件内,需要进行对比找出,相比下这种方法更符合常规思路,直接把邻接表作为参数,复用时会有问题!!!!!改成文件名! 还有就是并发异常!
*
* @param srcFile
* @param incFile
* @return
* @throws IOException
* @throws NumberFormatException
*/
public static TreeMap<Integer, HashSet<Integer>> joinUndirAdjList2(
String srcFile, String incFile) throws NumberFormatException,
IOException {
TreeMap<Integer, HashSet<Integer>> mixedAdjList = AdjacencyList
.constructUnDirectedAdjList(srcFile);
try {
TreeMap<Integer, HashSet<Integer>> incAdjList = AdjacencyList
.constructUnDirectedAdjList(incFile); // 构建与新增文件对应的原始邻接表
for (Map.Entry<Integer, HashSet<Integer>> e : incAdjList.entrySet()) {
HashSet<Integer> values = e.getValue();
if(e.getKey()==9703336)
System.out.println("Test");
if (mixedAdjList.containsKey(e.getKey())) { // 如果src包含该key
for (Integer value : values) {
if (mixedAdjList.get(e.getKey()).contains(value))
continue; // 该新增边重复则跳过
if (mixedAdjList.containsKey(value)) { // 1.如果新增顶点和端点都在srcAdjList中且边不重复,则增加
mixedAdjList.get(e.getKey()).add(value);
mixedAdjList.get(value).add(e.getKey());
} else { // 2.如果新增顶点在,端点不在srcAdjList中,则增加
HashSet<Integer> newValues = new HashSet<Integer>();
newValues.add(e.getKey());
mixedAdjList.put(value, newValues);
mixedAdjList.get(e.getKey()).add(value);
}
}
} else {
for (Integer value : values) {
if (mixedAdjList.containsKey(value)) { // 3.如果新增key不在而value在
HashSet<Integer> newKeyValues = new HashSet<Integer>();
newKeyValues.add(value);
mixedAdjList.put(e.getKey(), newKeyValues); //这种做法会在第一个value生成keyValue对,但在第2个的时候生成新的kv对将前一个覆盖!
//比如27 | 51 39,假设mixedAdjList包含51,不包含<27,51>时会生成<27,51>,到39时会生成新的<27,39>,put会覆盖以前的<27,51>!
mixedAdjList.get(value).add(e.getKey());
} else {
HashSet<Integer> newKeyValues = new HashSet<Integer>(); // 4.如果新增key不在且value也不在
newKeyValues.add(e.getKey());
mixedAdjList.put(value, newKeyValues);
HashSet<Integer> newKeyValues2 = new HashSet<Integer>();
newKeyValues2.add(value);
mixedAdjList.put(e.getKey(), newKeyValues2);
}
}
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(mixedAdjList.get(9703336));
return mixedAdjList;
}

总结: put的时候一定要确保这个key当前是不存在的,否则可能会覆盖以前的value!


集合使用常见错误总结:
1.容器复用问题.(Java的指针?)
2.并发错误(
java.util.ConcurrentModificationException),尚未厘清原因.
3.put之前要确保key值不存在,否则会覆盖原有的value值!!!!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics