Java 创建新对象时,对象将覆盖自身

Java 创建新对象时,对象将覆盖自身,java,graph,graph-theory,edges,kruskals-algorithm,Java,Graph,Graph Theory,Edges,Kruskals Algorithm,我有点被这个节目困住了。现在,我有一个图形的边对象。此边对象具有一个权重和两个顶点对象。我为顶点对象创建了一个类,也为边对象创建了一个类: 顶点: public class Vertex { private final Key key; private Vertex predecessor; private Integer rank; public Vertex( String value ) { this.key = new Key( value );

我有点被这个节目困住了。现在,我有一个图形的边对象。此边对象具有一个权重和两个顶点对象。我为顶点对象创建了一个类,也为边对象创建了一个类:

顶点:

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;
}
}
顶点接受一个关键对象,它只是一个字符串和一个数字

边缘:

当我试图声明一个边缘对象时,它工作得很好。但是,当我创建第二个对象时,它会“覆盖”第一个对象

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


我已经在这个程序上呆了一段时间(其中有各种各样的问题),但就我的一生而言,我不明白为什么它会这样做。有人能指出我的错误吗?

因为您将字段定义为
静态
。静态字段属于类而不是对象。为了使对象有自己的字段,您不应该使用static关键字。创建新的边对象时,将使用新值覆盖这些静态字段

private static int weight;
private static Vertex A;
private static Vertex B;
更改如下

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