简体   繁体   English

Java-Groovy:以对象作为键进行映射

[英]Java - Groovy: Map with Objects as Key

I am having trouble on how to retrieve the Value from a Map indexed with custom Objects. 我在如何从使用自定义对象建立索引的地图中检索值时遇到麻烦。 In my case I have a Map with a Model object as Key and a List of objects as Value. 就我而言,我有一个Map,其中Model对象为Key,对象列表为Value。 The Map seems to be well populated because I've iterated through each Key and printed all Model objects to console. 由于我遍历了每个Key并将所有Model对象打印到控制台,因此Map似乎填充得很好。

My question is how to get Value from a specific entry in the Map. 我的问题是如何从地图中的特定条目获取价值。

Map<Model, Parameter> mapSet = m.getMyMap()

for(Entry<Model, Parameter> entry : mapSet){
    println entry.key.getModel() //prints each Model
}

List<Parameter> testListBase = mapSet.get(new Model("BASE"))

List<Parameter> testListSearch = mapSet.get(new Model("SEARCH"))

Do I have to override hashCode() and equals() from Object to retrieve the list for that entry in the Map? 我是否必须从Object覆盖hashCode()equals()来检索Map中该条目的列表?

UPDATE UPDATE

Here it is the simple Model object, but still cannot retrieve the key using 这里是简单的Model对象,但仍然无法使用

mapSet.get(new Model("BASE"))

public final class Model {

private final String model;
private final static int count = 0;
private int id;

private Model(String model){
    this.model = model;
    id = ++count;
}

private String getModel(){
    return model;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    result = prime * result + ((model == null) ? 0 : model.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    Model other = (Model) obj;
    if (id != other.id) {
        return false;
    }
    if (model == null) {
        if (other.model != null) {
            return false;
        }
    } else if (!model.equals(other.model)) {
        return false;
    }
    return true;
}

} }

Yes, Model must implement hashCode() and equals(Object) . 是的, Model必须实现hashCode()equals(Object)

...great care must be exercised if mutable objects are used as map keys. ...如果将可变对象用作地图键,则必须格外小心。 The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. 如果在对象是映射中的键的情况下,以影响等值比较的方式更改对象的值,则不会指定映射的行为。 - http://docs.oracle.com/javase/7/docs/api/java/util/Map.html -http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

You may be able to implement hashCode() and equals(Object) quite easily using Groovy's EqualsAndHashCode AST transformation. 使用Groovy的EqualsAndHashCode AST转换,您可能很容易实现hashCode()equals(Object) Here's a working example: 这是一个工作示例:

@groovy.transform.TupleConstructor
@groovy.transform.EqualsAndHashCode
class Model {
    String name
}

@groovy.transform.TupleConstructor
class Parameter {
    String name
}

Map<Model, List<Parameter>> mapSet = [
    (new Model('BASE')): [
        new Parameter('Some parameter'), 
        new Parameter('Another parameter')
    ],

    (new Model('SEARCH')): [
        new Parameter('Yet another parameter'), 
        new Parameter('And yet another parameter')
    ]
]

for(Map.Entry<Model, List<Parameter>> entry: mapSet) {
    println entry.key // Prints each Model
}

List<Parameter> testListBase = mapSet.get(new Model("BASE"))
List<Parameter> testListSearch = mapSet.get(new Model("SEARCH"))

assert testListBase*.name.containsAll(['Some parameter', 'Another parameter'])
assert testListSearch*.name.containsAll(['Yet another parameter', 'And yet another parameter'])

I used the TupleConstructor AST for convenience, but the work-horse here is EqualsAndHashCode . 为了方便起见,我使用了TupleConstructor AST,但是这里的主要工作是EqualsAndHashCode Note that I assumed your intention and therefore deviated from your example to code what you said : 请注意,我假设了您的意图,因此偏离了您的示例来编写您所说的内容

...a Map with a Model object as Key and a List of objects as Value. ...以Model对象为键,对象列表为Value的映射。

The EqualsAndHashCode documentation describes how to tweak the default behaviour, in case you need to. EqualsAndHashCode文档描述了在需要时如何调整默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM