1

I'd like to use the integer-id-value of my vertex-class as an index, in my Map-structure, without using a parallel data structure.

class Vertex {
    private int v;
    private int label;

    //...
}

I store vertex objects, in a Map<Vertex,ArrayList<Edge>> adjMap.

Is it possible use the v-property of my Vertex class, as an index-key in my Map?

gdm
  • 172
  • 1
  • 7

2 Answers2

1

It depends on the Map implementation you are using. For example, for a HashMap you can override equals and hashCode of your Vertex class so that two vertices will be considered equal if their v properties are equal.

class Vertex {
    private int v;
    private int label;

    public Vertex (int v)
    {
        this.v = v;
    }

    @Override
    public boolean equals (Object o)
    {
        if (!(o instanceof Vertex))
            return false;
        Vertex ov = (Vertex)o;
        return this.v == ov.v;
    }

    @Override
    public int hashCode ()
    {
        return v;
    }
}

Now, to locate the value for a given v value in your Map :

adjMap.containKey(new Vertex(v));
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Ok. Then your equals and hashcode should only use property v. Code below:

public class Vertex {

    private int v;
    private int label;

 public static void main(String[] args) {
    Map<Vertex, String> map = new HashMap<Vertex, String>();

    Vertex vertex = new Vertex();
    vertex.v = 5;
    vertex.label = 10; 

    map.put(vertex, "vertex");

    Vertex vertex2 = new Vertex();
    vertex2.v = 5;
    vertex2.label = 100;  

    System.out.println("Value:: "+ map.get(vertex2));
}

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + v;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Vertex other = (Vertex) obj;
        if (v != other.v)
            return false;
        return true;
    }
}

Output: Value:: vertex

TheCodingFrog
  • 3,406
  • 3
  • 21
  • 27