2014-11-02 63 views
0

我很困惑這個程序。截至目前,我有一個圖形的邊緣對象。該邊緣對象需要一個權重和兩個頂點對象。我已經創建了一個頂點對象的類,以及爲邊緣對象的類:對象在創建新對象時覆蓋本身

頂點:

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。靜態字段屬於類而不是對象。爲了讓對象擁有自己的字段,您不應該使用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 2014-11-02 01:53:11