2014-11-02 2 views
0

나는이 프로그램에 익숙하지 않습니다. 지금은 그래프에 Edge 개체가 있습니다. 이 에지 객체는 가중치와 두 개의 꼭지점 객체를 사용합니다.새 개체가 만들어지면 개체가 덮어 씁니다.

정점 :

public class Vertex { 
private final Key key; 
private Vertex predecessor; 
private Integer rank; 

public Vertex(String value) 
{ 
    this.key   = new Key(value); 
    this.predecessor = null; 
    this.rank   = null; 
} 

/** 
* Return the key of the vertex. 
* @return key of vertex 
*/ 
public Key get_key() 
{ 
    return this.key; 
} 

/** 
* Set the predecessor of the vertex. 
* @param predecessor parent of the node 
*/ 
public void set_predecessor(Vertex predecessor) 
{ 
    this.predecessor = predecessor; 
} 

/** 
* Get the predecessor of the vertex. 
* @return vertex object which is the predecessor of the given node 
*/ 
public Vertex get_predecessor() 
{ 
    return this.predecessor; 
} 

/** 
* Set the rank of the vertex. 
* @param rank integer representing the rank of the vertex 
*/ 
public void set_rank(Integer rank) 
{ 
    this.rank = rank; 
} 

/** 
* Get the rank of the vertex. 
* @return rank of the vertex 
*/ 
public Integer get_rank() 
{ 
    return this.rank; 
} 
} 

정점 그냥 문자열과 숫자 키 오브젝트를 나는 정점 객체에 대한 클래스뿐만 아니라 가장자리 객체의 클래스를 만들었습니다.

가장자리 :

public class Edge { 
private static int weight; 
private static Vertex A; 
private static Vertex B; 

public Edge(Vertex A, Vertex B, int weight) 
{ 
    Edge.A  = A; 
    Edge.B  = B; 
    Edge.weight = weight; 
} 

public int get_weight() 
{ 
    return Edge.weight; 
} 

public Vertex get_vertex_1() 
{ 
    return Edge.A; 
} 

public Vertex get_vertex_2() 
{ 
    return Edge.B; 
} 
} 

내가 가장자리 객체를 선언 할 때, 그냥 잘 작동합니다. 그러나 두 번째 객체를 만들면 첫 번째 객체를 "덮어 씁니다".

Edge AE = new Edge(new Vertex("A"), new Vertex("E"), 5); 

키 값 (이 경우 A 또는 E)을 인쇄하는 메서드를 호출하면 올바르게 작동합니다. 그러나, 내가 이것을 할 때 :

Edge AE = new Edge(new Vertex("A"), new Vertex("E"), 5); 
Edge CD = new Edge(new Vertex("C"), new Vertex("D"), 3); 

CD는 기본적으로 AE를 덮어 씁니다. 그래서 AE에서 "A"를 얻으 려 할 때 나는 C를 얻습니다. E를 얻으려고하면 D가 생깁니다.

저는이 프로그램에 조금 이나마 끼어 들었습니다. ,하지만 내 인생에서 왜 이런 일을하는지 알 수 없습니다. 아무도 내 오류를 지적하시기 바랍니다 수 있습니까?

답변

1

필드를 static으로 정의했기 때문에. 정적 필드는 객체가 아닌 클래스에 속합니다. 개체가 자신의 필드를 갖기 위해서는 정적 키워드를 사용하면 안됩니다. 새 Edge 객체를 만들 때 이러한 정적 필드를 새 값으로 덮어 씁니다.

private static int weight; 
private static Vertex A; 
private static Vertex B; 

다음과 같이 변경하십시오.

private int weight; 
private Vertex A; 
private Vertex B; 
+1

정말 고마워요. – Hannah

관련 문제