简体   繁体   English

Java:带有两个键的HashMap

[英]Java: HashMap with two keys

i'm trying to build a HashMap having two keys in this way: first i created a class which is only a data structure. 我正在尝试用这种方式构建一个有两个键的HashMap:首先我创建了一个只是数据结构的类。

public class Tarta {
    public String nome;
    public String data;

    public Tarta(String nome, String data) {
        this.nome = nome;
        this.data = data;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

Then i populated my map by writing this in another class: 然后我通过在另一个类中写这个来填充我的地图:

mappaTarta.put(new Tarta(nome, data), peso);

During compilation i had no errors, but when testing i got null, for example: 在编译期间我没有错误,但是在测试时我得到了null,例如:

System.out.println(lr.leggiRecord().get(new Tarta("R", "15/11/2015")));

Can you kindly explain me why? 你能解释一下为什么吗? Thankyou 谢谢

If you want to use items as keys in a HashMap , you need to override their equals and hashCode methods. 如果要在HashMap使用项目作为键,则需要覆盖它们的equalshashCode方法。 Otherwise, the default implementations will consider two instances created with identical parameters as different, because they are two different instances. 否则,默认实现将考虑使用相同参数创建的两个实例,因为它们是两个不同的实例。

Currently: 目前:

Tarta a = new Tarta("foo", "bar");
Tarta b = new Tarta("foo", "bar");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // false
System.out.println(a.hashCode() == b.hashCode()); // false

Example implementations: 示例实现:

@Override public boolean equals(Object other) {
  if (other == this) return true;
  if (other instanceof Tarta) {
    Tarta that = (Tarta) other;
    return Objects.equals(this.name, that.name)
        && Objects.equals(this.data, that.data);
  }
  return false;
}

@Override public int hashCode() {
  return Objects.hash(name, data);
}

Then: 然后:

Tarta a = new Tarta("foo", "bar");
Tarta b = new Tarta("foo", "bar");
System.out.println(a == b); // false - they are still different instances
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true

Note that it is also advisable only to use immutable objects as keys in HashMaps: you should make name and data final at the very least, and make the class final too to make it truly immutable. 请注意,建议仅将不可变对象用作HashMaps中的键:您应该至少将namedata设为final ,并使类也final使其成为真正不可变的。

Java VM uses the Object.hashCode() and Object.equals(Object) to compare object so basicaly it dont know how to compare the Tarta Object and you need to override those methods i mentioned to work! Java VM使用Object.hashCode()和Object.equals(Object)比较对象,所以基本上它不知道如何比较Tarta对象,你需要覆盖我提到的那些方法! Sory about my english Sory关于我的英语

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

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