如何在 Java 集中更改使用的比较器



我目前正在使用一个无向图,并试图获得一个包含所有边缘而没有重复项的集合(所以如果已经有 e(开始 2、结束 1、权重 5(,则不需要边缘 e(开始 1、结束 2、权重 5(。

我最初的目的是使用 Set 来解决这个问题,但我不确定 Set 如何找到重复项以及如何为 Set 定义它们。似乎有一个选项可以检查使用的比较器,但我找不到任何关于更改它的信息。

如果有人能帮助我提出一些想法,那就太好了。

一个简单的解决方案是将类设置为"Edge"并保存边缘的开始、结束和权重,如下所示:

public class Edge {
String start = "";
String end = "";
int weight = 0;
public Edge(String start, String end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
//check if the edge is the same with the intance
public boolean isSameEdge(Edge edge) {
if ((this.start.equals(edge.start) && this.end.equals(edge.end) && this.weight == edge.weight)) {
return true;
}
return this.start.equals(edge.end) && this.end.equals(edge.start) && this.weight == edge.weight;
}
@Override
public String toString() {
return "Edge{" +
"start='" + start + ''' +
", end='" + end + ''' +
", weight=" + weight +
'}';
}
}

然后在您的主程序中创建边缘实例并将它们添加到 ArrayList 中,但首先检查它们是否已经在列表中。

ArrayList<Edge> edgeArrayList = new ArrayList<>();
Edge edge1 = new Edge("a", "b", 5);
Edge edge2 = new Edge("b", "a", 5);
boolean hasSame = false;
edgeArrayList.add(edge1);
for (Edge edge : edgeArrayList) {
if (edge.isSameEdge(edge2)) {
hasSame = true;
}
}
if (!hasSame) {
edgeArrayList.add(edge2);
}
System.out.println("List of edges: " + Arrays.toString(edgeArrayList.toArray()));

输出将仅是边 1,因为边 1 和边 2 相同。

List of edges: [Edge{start='a', end='b', weight=5}]

最新更新