lucad93
lucad93

Reputation: 45

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.

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:

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

Can you kindly explain me why? Thankyou

Upvotes: 2

Views: 1092

Answers (2)

Ivan Vilanculo
Ivan Vilanculo

Reputation: 668

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! Sory about my english

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140514

If you want to use items as keys in a HashMap, you need to override their equals and hashCode methods. 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.

Upvotes: 13

Related Questions