当前位置: 代码迷 >> java >> 使用Map结构使用特定的对象属性进行索引
  详细解决方案

使用Map结构使用特定的对象属性进行索引

热度:36   发布时间:2023-07-16 17:47:56.0

我想在我的Map结构中使用我的顶点类的integer-id-value作为索引,而不使用并行数据结构。

class Vertex {
    private int v;
    private int label;

    //...
}

我将顶点对象存储在Map<Vertex,ArrayList<Edge>> adjMap

是否可以将Vertex类的v属性用作Map中的索引键?

这取决于您使用的Map实现。 例如,对于HashMap,您可以覆盖Vertex类的equalshashCode ,这样,如果两个顶点的v属性相等,则它们将被视为相等。

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

现在,要在地图中找到给定v值的值:

adjMap.containKey(new Vertex(v));

好。 然后,您的equalshashcode应该仅使用属性v。下面的代码:

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

输出:值::顶点

  相关解决方案