2011-09-14 5 views
1

방향이 지정되지 않은 스파 스 그래프에서 사용할 사용자 정의 가장자리 및 정점 유형을 정의했습니다. 문제는 그래프가 원하지 않는 여러 가장자리를 추가한다는 것입니다. 예를 들어, 아래의 코드를 고려하면 :JUNG - 사용자 정의 가장자리 및 꼭지점 문제

UndirectedSparseGraph<Vertex, Edge> graphX = new UndirectedSparseGraph<Vertex, Edge>(); 
graphX.addEdge(new Edge("1#2"), new Vertex("1"), new Vertex("2")); 
graphX.addEdge(new Edge("1#2"), new Vertex("1"), new Vertex("2")); 
graphX.addEdge(new Edge("2#1"), new Vertex("2"), new Vertex("1")); 
graphX.addEdge(new Edge("1#3"), new Vertex("1"), new Vertex("3")); 
graphX.addEdge(new Edge("1#4"), new Vertex("1"), new Vertex("4")); 

나는 두 개의 비슷한 가장자리 (첫 번째 것)를 고의로 추가했습니다. Edge와 Vertex와 같은 두 가지 클래스에 대해 equals 메서드를 재정의했습니다. 그러나 그래프는 꼭지점이 다르기 때문에 가장자리로 가정하고 모두를 추가합니다. 출력은 다음과 같습니다.

Vertices:1,4,1,1,2,1,1,2,2,3 
Edges:1#3[1,3] 1#4[1,4] 1#2[1,2] 1#2[1,2] 2#1[2,1] 

그래서 내가 뭘 잘못하고 있니?

추신. 참고하시기 바랍니다. 내가 만든 클래스는 다음과 같습니다.

public class Vertex { 

    private String id; 
    //More info in the future 

    public Vertex(String id){ 
     this.id = id; 
    } 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    @Override 
    public boolean equals(Object obj){ 
     return ((Vertex) obj).id.equals(this.id); 
    } 

    @Override 
    public String toString(){ 
     return this.id; 
    } 

} 

public class Edge { 

    private String id; 
    private double weight; 

    public Edge(String id, double weight){ 
     this.id = id; 
     this.weight = weight; 
    } 

    public Edge(String id){ 
     this.id = id; 
     this.weight = -1; 
    } 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public double getWeight() { 
     return weight; 
    } 

    public void setWeight(double weight) { 
     this.weight = weight; 
    } 

    @Override 
    public boolean equals(Object obj){ 
     return ((Edge) obj).id.equals(this.id); 
    } 

    @Override 
    public String toString(){ 
     return this.id; 
    } 

} 

답변

2

이것은 정크만의 문제가 아니라 고전적인 Java 문제입니다. 기본적으로 equals()를 오버라이드하지만 hashCode()를 오버라이드하지 않으므로 해시 코드가 "equals()"와 일치하지 않습니다. 자세한 내용과 몇 가지 솔루션에 대한이 질문과 답변을 참조하십시오. How to ensure hashCode() is consistent with equals()?

관련 문제