【问题标题】:Java how to get value from Map by key-objectJava如何通过键对象从Map中获取值
【发布时间】:2021-01-26 23:19:20
【问题描述】:

我正在用 java 进行图形实现。我有以下问题: 我无法通过键从 HashMap 中获取值,这是一个模板化的类对象, 更准确地说,我需要获得一个值,其二进制表示中的键等于指定的键对象,但不是(它们在内存中具有不同的地址)。据我了解,get(..) 方法返回一个值,其键地址等于指定的值。如果不进行愚蠢的搜索,我不知道该怎么做。顺便说一句,我是用 C++ 写的,对 Java 的理解不是很好。

这是有问题的代码:

public void addEdge(V v1, V v2, E edg) {        
        nodes.get(new Vertex<V>(v1)).put(new Vertex<V>(v2), new Edge<E>(edg));
        nodes.get(new Vertex<V>(v2)).put(new Vertex<V>(v1), new Edge<E>(edg));
    }

这是整个代码:

import java.util.*;

class Vertex<Node> {
    Node node;
    int id;

    Vertex(Node val) {
        this.node = val;
    }

    Vertex(Node val, int id) {
        this.node = val;
        this.id = id;
    }
}

class Edge<T> {
    T value;

    Edge(T val) {
        this.value = val;
    }
}

public class Graph<V, E> {
    private Map<Vertex<V>, HashMap<Vertex<V>, Edge<E>>> nodes;

    Graph() {
        nodes = new HashMap<Vertex<V>, HashMap<Vertex<V>, Edge<E>>>();      
    }

    public void addVertex(V ver, int id) {
        nodes.put(new Vertex<V>(ver, id), new HashMap<Vertex<V>, Edge<E>>());
    }

    public void addEdge(V v1, V v2, E edg) {
        
        nodes.get(new Vertex<V>(v1)).put(new Vertex<V>(v2), new Edge<E>(edg));
        nodes.get(new Vertex<V>(v2)).put(new Vertex<V>(v1), new Edge<E>(edg));
    }

    public V getNode(int id) {
        for(Vertex<V> el: nodes.keySet())
            if(el.id == id)
                return el.node;
        return null;
    }
}

【问题讨论】:

    标签: java dictionary object hashmap


    【解决方案1】:

    来自https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#get-java.lang.Object-

    public V get(对象键)

    返回指定键映射到的值,如果此映射不包含该键的映射,则返回 null。

    更正式地说,如果此映射包含从键 k 到值 v 的映射,满足 >(key==null ? k==null : key.equals(k)),则此方法返回 v;否则 > 返回 null。 (最多可以有一个这样的映射。)

    您需要在您的顶点中实现 equals(),否则它只会查看必须是原始对象的默认 equals()。

    类似

    @Override
    public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Vertex that = (Vertex) o;
            if (node != null ? !node.equals(that.node) : that.node != null) return false;
            return this.id == that.id;
    }
    

    重要提示: 此外,您需要实现 hashcode() 以使其在 HashMap 中工作,或实现 compareTo() 以实现树形映射。

    https://www.baeldung.com/java-hashcode等教程

    【讨论】:

    • 我理解在同一个地方我不指定id,分别,这些对象不相等,那么你的答案是正确的。
    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 2019-02-02
    • 2018-04-18
    • 2016-09-06
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多