2014-11-02 46 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