Java Map store custom object

Description

Java Map store custom object

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String args[]) {
    Langugage c1 = new Langugage(1, "CSS");
    Langugage c2 = new Langugage(2, "HTML");
    Langugage c3 = new Langugage(3, "Java");

    Langugage c4 = new Langugage(1, "new CSS");
    Langugage c5 = new Langugage(2, "new HTML");
    Langugage c6 = new Langugage(3, "demo2s.c om");

    Map<Integer, Langugage> map = new HashMap<Integer, Langugage>();
    map.put(c1.getId(), c1);//from  www .  j  a  va2  s .  com
    map.put(c2.getId(), c2);
    map.put(c3.getId(), c3);
    map.put(c4.getId(), c4);
    map.put(c5.getId(), c5);
    map.put(c6.getId(), c6);

    System.out.println(map);
  }

}

class Langugage {
  public Langugage(int id, String name) {
    this.id = id;
    this.name = name;
    this.creationTme = new Date();
  }

  private Integer id;
  private String name;
  private Date creationTme;

  public int getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Date getCreationTme() {
    return creationTme;
  }

  public void setCreationTme(Date creationTme) {
    this.creationTme = creationTme;
  }

  @Override
  public int hashCode() {
    return this.id;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Langugage && ((Langugage) obj).id == this.id)
      return true;
    else
      return false;
  }

  public String toString() {
    final String TAB = " ";

    String retValue = "";

    retValue = "id = " + this.id + TAB + "name = " + this.name
        + TAB + "creationTme = " + this.creationTme.getTime() + TAB;

    return retValue;
  }
}



PreviousNext

Related