【问题标题】:Adjacency Matrix Implementation邻接矩阵实现
【发布时间】:2014-05-04 19:11:28
【问题描述】:
我正在寻找在第一行和第一列有键的矩阵的实现。
首先,我认为 HashMap 中有类似 HashMap 的东西,但这看起来很难看,我认为这是错误的。
我真的需要那些我可以检查的键,如果第一行中存在一个字符串作为键。
(我想实现一个邻接矩阵)
我不确定我是否足够清楚。这里有一张小图片来可视化它。
类似这样的:
只是第一列和第一行不是数字而是城市。
事实上,我想将城市之间的距离保存在邻接矩阵中。
【问题讨论】:
标签:
java
matrix
adjacency-matrix
【解决方案1】:
使用自定义类作为 HashMap 中的键。
public class Key {
private String city1;
private String city2;
public Key(String city1, String city2){
this.city1 = city1;
this.city2 = city2;
}
//hashCode and equals
}
那么你可以这样使用它:
HashMap<Key, Integer> adjacencyMatrix = new HashMap<>();
adjacencyMatrix.put(new Key("Berlin", "London"), 933);
Integer distance = adjacencyMatrix.get(new Key("Berlin", "Paris"));
if (distance == null){
//no entry
}
不要忘记在 Key 类中生成 hashCode 和 equals!