Search code examples
javagraphgraph-theoryedgeskruskals-algorithm

Object overwrites itself when new object is made


I'm kind of stuck on this program. As of now, I have an Edge object for a graph. This edge object takes a weight and two Vertex objects. I have created a class for the Vertex object, as well as a class for the Edge object:

Vertex:

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 takes a Key object which is just a string and a number.

Edge:

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;
} 
}

When I try to declare an Edge object, it works just fine. However, when I create a second one, it "overwrites" the first object.

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

When I call the methods to print the value of the key (in this case, either A or E), it works just fine. However, when I do this:

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

CD basically overwrites AE. So when I try to get "A" from AE, I get C. When I try to get E, I get D.

I've been stuck on this program for a little while (various different problems in it), but for the life of me, I can't figure out why it's doing this. Can anyone please point out my error?


Solution

  • Because you define fields as static. Static fields belong to class not to objects. In order objects to have their own fields you should not use static keyword. When you create a new Edge object, you overwrite these static fields with new values.

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

    Change as below.

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