Java Map create map using custom object as key

Description

Java Map create map using custom object as key

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    Language e1 = new Language(1);
    Language e2 = new Language(2);

    HashMap<Language, Integer> map = new HashMap<>();
    map.put(e1, 1);// w ww . ja va 2 s. c o m
    map.put(e2, 2);

    System.out.println(map.get(e1));
    System.out.println(map);

    e1.setValue(0);
    System.out.println(map.get(e1));
    System.out.println(map);

    e1.setValue(2);
    System.out.println(map.get(e1));
    System.out.println(map);

    Language e3 = new Language(2);
    System.out.println(map.get(e3));
  }
}

class Language {
  private int n;

  public Language(int n) {
    this.n = n;
  }

  public void setValue(int n) {
    this.n = n;
  }

  @Override
  public int hashCode() {
    return n;
  }

  @Override
  public boolean equals(Object e) {
    if (this == e)
      return true;
    if (!(e instanceof Language))
      return false;
    Language an = (Language) e;
    return n == an.n;
  }

  @Override
  public String toString() {
    return "Language [n=" + n + "]";
  }

}



PreviousNext

Related