0

I have a requirement to fetch values from

Map<Object1, Object2>() objectMap= new HashMap<Object1, Object2>();
Object1 obj1 = new Object1();
Object2 obj2 = new Object2();

//Object1 class:
public class Object1{
    private String name;
    private String id;
    private String number;

//along with getters and setters
}

//Object2 class:
public class Object2{
   private String value1; 
   private String value2;

//along with getters and settersenter code here
}

objectMap.put(obj1, obj2);
Object1 obj3 = new Object1();

obj3 has values same as obj1, i.e all the fields, name, value and number as the same for obj3.

I need to fetch value of map using obj3 if obj1 equals obj3. How do I check obj1 equals to obj3 and then how do I fetch map value using obj3?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Smrithi
  • 45
  • 1
  • 3
  • 2
    `Object1 obj1 = new Object1();` `Object1 obj3 = new Object1();`. Here, `obj1` and `obj3` are not `equal` unless you implement `equals` and `hashCode` – Thiyagu Mar 03 '18 at 08:15
  • 3
    Possible duplicate of [Why do I need to override the equals and hashCode methods in Java?](https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – Thiyagu Mar 03 '18 at 08:16

2 Answers2

0

so you start like this

objectMap.put(obj1, obj2);

Now in your Map you have a single key/value pair. If you then call

objectMap.get(obj1);

you will get obj2 back. This is because the object you are using for the lookup has the same hashCode and is 'equal()' to the object used for the put.

If you then do this

objectMap.get(obj3);

you will get obj2 back. This is again because the object you are using for the lookup has the same hashCode and is 'equal()' to the object used for the put.

so.

If you do:

Object1 o1 = null;
if (obj1.equals(obj3) { 
  o1 = objectMap.get(obj1);
}

The you will retrieve the value you want from the map only if the keys are equal. Obviously the if statement is completely redundant, it is there to prove the point of the keys being equal in order for this to work. Obviously your class Object1 needs equals and hashcode implemented for this to work.

paulturnip
  • 106
  • 5
-1
Map<K,V> map=new Hash Map<K,V>();

for(Map.Entry m= map.entry Set())

{

m.put(object 1); m.put(object 2);

}