我有一个名为 Node 的类。对于 Node 的实例,我想分配一个字典作为属性来跟踪 Node 对象的邻居以及连接 Node 到其每个邻居的路径的权重。
示例:
1->2---7(节点1连接节点2,权重为7)
1->3---5(节点1连接节点3,权重为5)
...
我想创建一个 Node 对象“1”,它有一个 Dictionary 属性,其中(键,值)等于(邻居,权重)。
在这种情况下 1 的字典应该是 [2:7, 3:5]。
import java.util.Dictionary;
public class Node{
public int i;
public Dictionary neighbors = new Dictionary();
public int w;
public Node(int i, int j, int weight){
this.i = i;
this.neighbors = neighbors.put(j, weight);
}
}
当前错误:./Node.java:6:错误:字典是抽象的;无法实例化
这可能吗?如果是这样,它会是什么样子?
最佳答案
The
Dictionary
class is the abstract parent of any class, such asHashtable
, which maps keys to values.NOTE: This class is obsolete. New implementations should implement the
Map
interface, rather than extending this class.
使用 map
。
Map<Node, Integer> neighbors = new HashMap<>();
// ...
neighbors.put(j, weight);
关于java - 我可以将字典指定为另一个类实例的属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29741512/