Custom object without implement the hashcode and equals methods store into HashMap


package com.test.model;

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

/***
 * custom object without implement the hashcode and equals used in the Hashmap
 * This program used to how custom object handle in HashMap
 * @author Prakash
 * */
public class HashMapTest {

public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Employee,Employee> map = new HashMap<>();
Employee e1 = new Employee(1,"Senthil");
Employee e2 = new Employee(1,"Senthil");

/**
* write e1 custom object store to hashmap 
* without override the hashcode and equals method
* output 
* put(e1,e1) : null
* because of this the first entry in the map
**/
System.out.println("put(e1,e1) : " + map.put(e1,e1));

/***
* Get the e1 object and print 
* Output
* get(e1)    : id :1 name:Senthil
   * e1 reference pointing to same object which added in the hashmap
 * hence e1 object is accessable
*/
System.out.println("get(e1)    : " + map.get(e1));

/***
* Get the e2 object but the content is same as e1 object 
* Output
* get(e2)    : null
* Unable to fetch the e2 object, eventhough e1 and e2 objects content are same
* but two object are different.
*/
System.out.println("get(e2)    : " + map.get(e2));
}

}

***
 * Employee Object implement without using hashcode and equals methods
 */
class Employee{
int id;
String name;

Employee(){

}

Employee(int id, String name){
this.id = id;
this.name = name;
}

public String toString(){
return "id :" +  id + " name:" + name;
}
}

Comments

Popular posts from this blog

Robotic Process Automation

WorkFusion

7 Rules of Success A.P.J Abdul Kalam