我有点被这个程序困住了。截至目前,我有一个图形的 Edge 对象。该边缘对象采用一个权重和两个顶点对象。我已经为 Vertex 对象创建了一个类,也为 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;
}
}
Vertex 接受一个 Key 对象,它只是一个字符串和一个数字。
边缘:
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 对象时,它工作得很好。但是,当我创建第二个对象时,它会“覆盖”第一个对象。
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。当我尝试从 AE 中得到“A”时,我会得到 D。
我已经在这个程序上停留了一段时间(其中有各种不同的问题),但对于我的一生,我无法弄清楚它为什么这样做。谁能指出我的错误吗?
最佳答案
因为您将字段定义为静态
。静态字段属于类而不是对象。为了使对象拥有自己的字段,您不应使用 static 关键字。当您创建新的 Edge 对象时,您可以使用新值覆盖这些静态字段。
private static int weight;
private static Vertex A;
private static Vertex B;
更改如下。
private int weight;
private Vertex A;
private Vertex B;
关于java - 创建新对象时对象会覆盖自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26695184/