java


Override equals method to return false while inserting to HashMap


import java.util.HashMap;
import java.util.Map;
public class MapTest {
public String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int hashCode(){
return 100;
}
#Override
public boolean equals(Object te){
return false;
}
public static void main(String[] args) {
MapTest obj = new MapTest();
MapTest obj1 = new MapTest();
obj.setId("test");
obj1.setId("test2");
Map<MapTest,Integer> test = new HashMap<MapTest,Integer>();
test.put(obj, 1000);
test.put(obj1, 2000);
test.put(new MapTest(), 4000);
System.out.println(test.get(obj)); //1000
System.out.println(test.get(obj1));//2000
System.out.println(test.get(new MapTest()));//Null
System.out.println(test.size());//3
}
}
Here the object returns same hashcodes so inorder to avoid overwriting while adding data to HashMap I have a equals method that returns false. Now when I use get I get the proper data example obj1 and obj are giving exact values but my question is when both their hashcodes are same how java distinguishes different objects and return their exact values from hashmap.
The answer is in how HashMap implements the get method. When it checks the equality of the given key against the keys stored in the map (when they have equal hashcode value), it first does a reference equality check. The code below is taken from Java 8's implementation of get and as you see, there is the == check for the keys.
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
If you use another object, with the same id value, it will not work, as there is no structural equality defined in your objects. Try this:
TestMap obj2 = new TestMap();
obj2.setId("test");
System.out.println(test.get(obj2)); // Returns Null
The hashcode equals is the first requirement for hashmap to decide whether two keys the same, but not the only one/
(key1 == key2 || key1.equals(key2)) is also needed.
If you change your equals method to always return true, you can see there will be only one element in the map at last.

Related Links

Twitter Spring Social - filter does not work
JAXB ClassCastException due to root element having the same tag as its child element
how to add int value to Set<Integer> (HashSet<Integer>)?
How to format the double values in JavaFX TableView [duplicate]
Java override annotation value by value provided in another annotation on the same class member
AlertDialog.Builder helper class cannot resolve constructor
Eclipse Maven Java import not resolved
how to remove empty line in a file in java
Changing string with same variable name in for loop
JSF Passing a POJO through Session
Instead of using synchronized keyword i am using lock concept but i am not getting the output as i got in synchronized key word?
Static context saved in Application class and used in a singleton toast builder, does this create a memory leak?
How to assign random numbers (0-10) to strings stored in a linkedlist
I'm getting this error using Java Mail API
Some nethods in my main Activity are showing as never used
How to see the arguments types of the methods from the superclasses when overriding methods in IntelliJ?

Categories

HOME
deployment
keras
c#-4.0
spagobi
kalman-filter
setup-deployment
jxls
gorm
google-cloud-ml
task
event-handling
opentracing
ef-migrations
database-replication
oxyplot
lldb
core-text
angular2-aot
smb
spark-jobserver
pingfederate
uninstall
ejabberd-module
objectanimator
primitive
preg-match
fabric8
semantic-versioning
jspresso
google-qpx-express-api
fog
kendo-ui-grid
repo
uiswipegesturerecognizer
openoffice.org
jmonkeyengine
revolution-slider
file-format
bitbucket-pipelines
scaffold
sharefile
theano.scan
xenforo
greenrobot-eventbus
graphenedb
pdf-reactor
bootstrap-dialog
node-sass
websphere-mq-fte
google-datalayer
xml-documentation
azure-application-gateway
revapi
worksheet
pnotify
mu
sybase-asa
ifs
linode
sqldf
crosswalk-runtime
topbeat
deadbolt-2
instant
infix-notation
android-textview
trash
autorest
holder.js
superstack
bluemix-app-scan
system.management
freedesktop.org
hsv
intellij-14
operation
nsight
website-monitoring
gui-test-framework
googlemock
castle
project-planning
google-reader
oracle-warehouse-builder
java.nio.file
soundtouch
mqx
type-equivalence
drools-planner
cassini-dev
anonymous-methods
dmoz
unc
sublist
datawindow
hosts-file
onsubmit
ocx
transactionscope
mercurial-server
libc++
hamachi
f#-powerpack
xmemcached
horizontal-accordion
netbeans-7.1
celltable
subviews
wise
preference
multi-tier
boost-smart-ptr

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App