带有 ArrayList 的 Hashmap 的 getOrDefault
我正在使用此代码来计算图中节点的传入边缘
for (Edge newEdge : edges) {
// Ingoing edges
if (inGoingEdges.containsKey(newEdge.destinationnode)) {
//System.out.println("All good");
} else {
inGoingEdges.put(newEdge.destinationnode, new ArrayList<Edge>());
}
ArrayList<Edge> inEdges = inGoingEdges.get(newEdge.destinationnode);
if (inEdges == null) {
inEdges = new ArrayList<Edge>();
inEdges.add(newEdge);
inGoingEdges.put(newEdge.sourcenode, inEdges);
}
else {
if (!inEdges.contains(newEdge)) {
inEdges.add(newEdge);
inGoingEdges.put(newEdge.sourcenode, inEdges);
}
}
,其中 inGoingEdges 是以下 HashMap :
private HashMap<Node,ArrayList<Edge>> inGoingEdges = new HashMap<Node,ArrayList<Edge>>();
在我的代码的某个时刻,我使用以下函数:graph.getIncomingEdges(firstNode)但对于某些节点,没有与某些节点匹配的 ArrayList,并且它返回空点错误。
我如何正确使用 getorDefault 函数来修复错误?
i'm using this code to compute the in going edges of a node in a graph
for (Edge newEdge : edges) {
// Ingoing edges
if (inGoingEdges.containsKey(newEdge.destinationnode)) {
//System.out.println("All good");
} else {
inGoingEdges.put(newEdge.destinationnode, new ArrayList<Edge>());
}
ArrayList<Edge> inEdges = inGoingEdges.get(newEdge.destinationnode);
if (inEdges == null) {
inEdges = new ArrayList<Edge>();
inEdges.add(newEdge);
inGoingEdges.put(newEdge.sourcenode, inEdges);
}
else {
if (!inEdges.contains(newEdge)) {
inEdges.add(newEdge);
inGoingEdges.put(newEdge.sourcenode, inEdges);
}
}
where inGoingEdges is the following HashMap :
private HashMap<Node,ArrayList<Edge>> inGoingEdges = new HashMap<Node,ArrayList<Edge>>();
At some point of my code i use the following function : graph.getIncomingEdges(firstNode) but for some nodes there is no ArrayList that matches to some nodes and it returns a nullpoint error.
How can i use the getorDefault function correctly in order to fix the error ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能不需要
getOrDefault
,因为这不会添加新列表。您可能想要的是computeIfAbsent。您为其提供一个函数,该函数将键作为参数,如果尚不存在则返回一个值。如果已经有一个值,则返回该值并忽略该函数。您还可以在您提供的代码中使用它来使其更加简洁:You probably don't want
getOrDefault
, because that doesn't add the new list. What you probably want iscomputeIfAbsent
. You provide it with a function that takes the key as argument and returns a value if none exists yet. If there already is a value, that is returned and the function is ignored. You can also use that in the code you provided to make it all less verbose: