How to avoid inserting duplicate objects in List? - java

I have two employee objects
Employee e1 = new Employee("1");
Employee e2 = new Employee("1");
So how to avoid inserting this second object in following List
List<Employee> list = new ArrayList<Employee>();
Can we use hashcode() and equals() methods to avoid inserting duplicate objects in the list? How?

Lists have a method to check if an object is in it or not. It internally uses the equals() method.
if(!list.contains(e2))
{
list.add(e2);
}

You can use Set to avoid inserting duplicates . But for that you need to override the hashCode() and equals() method of your Employee class to define what exactly is e1.equals(e2).

In your question, e1 and e2 are not really equal in terms of their hashcode. So you cant really equate it using .equals() or == or .hashCode().equals(). You will have to implement your own method to check for equality based on the data contained in these objects. To Java, every object instantiated using new will be a different object.
Below is excerpt from the Java Api doc for the hashcode method
The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must
consistently return the same integer, provided no information used
in equals comparisons on the object is modified. This integer need
not remain consistent from one execution of an application to
another execution of the same application.
If two objects are equal
according to the equals(Object) method, then calling the hashCode
method on each of the two objects must produce the same integer
result.
It is not required that if two objects are unequal according
to the equals(java.lang.Object) method, then calling the hashCode
method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing
distinct integer results for unequal objects may improve the
performance of hashtables.
As much as is reasonably practical, the hashCode method defined by
class Object does return distinct integers for distinct objects. (This
is typically implemented by converting the internal address of the
object into an integer, but this implementation technique is not
required by the JavaTM programming language.)

Related

What is the use of overriding hashCode in Java other than Collections API?

This question is asked by interviewer that most of answers related to hash code is used for bucketing where it checks equals to search objects.
Is there any other general use case or scenario, where hash code is beneficial and can be used in a routine program?
As recently I have used JPA where it throws exception "Composite-id class does not override hashCode()" but again it is used by implementation class of hibernate. Sly, what other places or scenario we can use hashcode other then collections especially scenario where you have used it yourself.
class a {
public int hashCode() {
}
}
class b {
public static void main(String[] str) {
//In what ways can i use hashcode here?
}
}
Let's say your class will not be used in any collection ever( which is very unlikely though), it will be used in more than one place and by other developers. Any developer using your class will expect that if two instances of that class are equal based on equals method, they should produce same hashCode value. This fundamental assumption will be broken if hashCode is not overridden to be consistent with equals and that will prevent their code to function properly.
From Effective Java , 3rd Edition :
ITEM 11: ALWAYS OVERRIDE HASHCODE WHEN YOU OVERRIDE EQUALS
You must override hashCode in every class that overrides equals. If
you fail to do so, your class will violate the general contract for
hashCode, which will prevent it from functioning properly in
collections such as HashMap and HashSet. Here is the contract, adapted
from the Object specification :
• When the hashCode method is invoked on an object repeatedly during
an execution of an application, it must consistently return the same
value, provided no information used in equals comparisons is modified.
This value need not remain consistent from one execution of an
application to another.
• If two objects are equal according to the equals(Object) method,
then calling hashCode on the two objects must produce the same integer
result.
• If two objects are unequal according to the equals(Object) method,
it is not required that calling hashCode on each of the objects must
produce distinct results. However, the programmer should be aware that
producing distinct results for unequal objects may improve the
performance of hash tables.
The key provision that is violated when you fail to override hashCode
is the second one: equal objects must have equal hash codes. Two
distinct instances may be logically equal according to a class’s
equals method, but to Object’s hashCode method, they’re just two
objects with nothing much in common. Therefore, Object’s hashCode
method returns two seemingly random numbers instead of two equal
numbers as required by the contract.
A small semantic mistake in the interview question. Hash code is not used to check equality, it's used to detect inequality. If hash codes are different the objects are guaranteed to be inequal. If the codes are equal the objects may be equal and need to be checked with the equals-method.
That said, if the hash code is cached, it could be used to speed up the equals method.
Suppose you only override equals but not hashCode
This means that hashCode is inherited from Object
Object.hashCode always tries to return different hash codes for different objects (regardless if they are equal or not)
This means that you may end up with different hash codes for two objects that you consider to be equal.
This in turn causes these two equal objects to end up in different buckets in hash based collections such as HashSet.
This causes such collections to break.
More reference: https://programming.guide/java/overriding-hashcode-and-equals.html

What is the interaction between hashSet structure, hashCode method and hash buckets?

Please explain the following statement:
The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.
The mentions of hash buckets and retrieval implies that a HashSet has some relation to a hash map as the HashSet interface only exposes add, remove and contains methods, no T retrieve(int hashCode) method.
Is it true that Hash Set uses hash codes and hash buckets internally? Or is it using Hash Map somehow instead?
There is a similar question asked in SCJP Certification about the hashcode method:
Q: 20 Which two statements are true about the hashCode method? (Choose two.)
A. The hashCode method for a given class can be used to test for
object equality and object inequality for that class.
B. The hashCode method is used by the java.util.SortedSet
collection class to order the elements within that set.
C. The hashCode method for a given class can be used to test for
object inequality, but NOT object equality, for that class.
D. The only important characteristic of the values returned by a
hashCode method is that the distribution of values must follow a
Gaussian distribution.
E. The hashCode method is used by the java.util.HashSet collection
class to group the elements within that set into hash buckets for
swift retrieval.
Answer: C, E
Explanation:(This explanation is taken from here)
If two objects are equal according to the equals(Object) method, then
calling the hashCode() method on each of the two objects must produce
the same integer result. It is NOT required that if two objects are
unequal according to the equals(java.lang.Object) method, then calling
the hashCode() method on each of the two objects must produce distinct
integer results. However, the programmer should be aware that
producing distinct integer results for unequal objects may improve the
performance of hashtables.
The values you add to a HashSet are actually set as keys of an underlying HashMap. A HashSet uses a HashMap under the hood. So, a HashMap's behavior should be expected for a HashSet as well.

understanding the relation between hashcode and equals method in Java [duplicate]

This question already has answers here:
Relationship between hashCode and equals method in Java [duplicate]
(7 answers)
Closed 8 years ago.
This is my understanding about hashcode and equals method :
if obj1.hashcode == obj2.hashcode (returns true) then obj1.equals(obj2) returns true and
if obj1.equals(obj2) returns false (returns true) then obj1.hashcode == obj2.hashcode (returns false)
is this correct?
The convention between equals() and hashCode() mandates this:
If an object is determined to be equal, then their hash code must* be equal. That is to say, if obj1.equals(obj2), then obj1.hashCode() == obj2.hashCode().
If an object is determined to not be equal, then there is no hard-and-fast rule for what their hash code should be between them. They could return the same hash code, but this may cause a multitude of errors.
*: This "must" is actually unenforceable at compile time or run time, so take it with a grain of salt. Just note that you jeopardize the correctness of your application with equals/hashCode usage if it is not implemented correctly.
if obj1.hashcode == obj2.hashcode (returns true) then obj1.equals(obj2) might return true
From the javadoc
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must
produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on
each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hash tables
That is incorrect. The documentation for Object.equals(Object) has a formal explanation of the contract for extending this method. Essentially the intent for the Object.equals method is to check if two objects are actually the same object. However it often makes sense to override this functionality and instead make your class' equals method determine whether two objects are logically equal to each other (for example, two different instances of String objects which both represent the same sentence).
On the other hand, Object.hashCode() specifies the following contract:
The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must
consistently return the same integer, provided no information used in
equals comparisons on the object is modified. This integer need not
remain consistent from one execution of an application to another
execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must
produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on
each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hash tables.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)
Basically, two different objects (either logically different or technically distinct) may have the same hashcode, because of how hashcodes are designed, but they should not be "equals". However, if two objects are equal to each other, they must have the same hashcode. Similarly, an object's hashcode may only change if the object itself changes in some way.
For further reading, see the Wikipedia article on hash functions.

Relationship between hashCode and equals method in Java [duplicate]

This question already has answers here:
What issues should be considered when overriding equals and hashCode in Java?
(11 answers)
Why do I need to override the equals and hashCode methods in Java?
(31 answers)
Closed 9 years ago.
I read in many places saying while override equals method in Java, should override hashCode method too, otherwise it is "violating the contract".
But so far I haven't faced any problem if I override only equals method, but not hashCode method.
What is the contract? And why am I not facing any problem when I am violating the contract? In which case will I face a problem if I haven't overridden the hashCode method?
The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.
As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().
If you have two objects which are .equals(), but have different hash codes, you lose!
The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().
This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.
According to the doc, the default implementation of hashCode will return some integer that differ for every object
As much as is reasonably practical, the hashCode method defined by class Object does
return distinct integers for distinct objects. (This is typically implemented by
converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)
However some time you want the hash code to be the same for different object that have the same meaning. For example
Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode
This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.
Yes, it should be overridden. If you think you need to override equals(), then you need to override hashCode() and vice versa. The general contract of hashCode() is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
The contract is that if obj1.equals(obj2) then obj1.hashCode() == obj2.hashCode() , it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.
Have a look at Hashtables, Hashmaps, HashSets and so forth. They all store the hashed key as their keys. When invoking get(Object key) the hash of the parameter is generated and lookup in the given hashes.
When not overwriting hashCode() and the instance of the key has been changed (for example a simple string that doesn't matter at all), the hashCode() could result in 2 different hashcodes for the same object, resulting in not finding your given key in map.get().
See JavaDoc of java.lang.Object
In hashCode() it says:
If two objects are equal according to the equals(Object) method,
then calling the hashCode method on each of the two objects must
produce the same integer result.
(Emphasis by me).
If you only override equals() and not hashCode() your class violates this contract.
This is also said in the JavaDoc of the equals() method:
Note that it is generally necessary to override the hashCode method
whenever this method is overridden, so as to maintain the general
contract for the hashCode method, which states that equal objects must
have equal hash codes.
A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.
Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

java - what happens if hashCode is not overriden? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what is an objects hashcode
Let's say that I create an object, called Employee which has id, firstName, lastName and email for instance variables and corresponding setter/getter methods. How is hashCode() calculated if I don't override hashCode() in Employee object when it is stored in collection objects?
If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.
Some collections, like HashSet, HashMap or HashTable use the hash code to store its data and to retrieve it. If you don't implement hashcode() and equals() in a consistent manner, then they will not function properly.
Edit:
As per Javadoc: Object.hashcode() is ''typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java(TM) programming language''. Therefore I would advise not to rely on a specific implementation. For what the implementations really do, see this answer to a similar question.
From the documentation:
As much as is reasonably practical, the hashCode method defined by
class Object does return distinct integers for distinct objects. (This
is typically implemented by converting the internal address of the
object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
So basically when you store in a Map/Set/somethingThatRequiresHashCode, the JVM will use the internal memory address of that instance to calculate the hashCode, guaranteeing (as much as hash functions guarantee anything - they don't) that each distinct instance will have a unique hashCode.
This is particularly important because of the Object contract regarding equals and hashCode, since:
The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null
reference values x and y, this method returns true if and only if x
and y refer to the same object (x == y has the value true).
If you don't override equals, it will compare the internal address of the two references, which matches the logic behind hashCode.
If your question is more related to: Will the JVM look at the values inside an instance to determine equality/calculate hashcode, the answer is simply no, if you do:
MyObject a = new MyObject("a", 123,"something");
MyObject b = new MyObject("a", 123,"something");
a and b will have different hashcodes.
From effective Java 2nd Edition
Item 9: Always override hashCode when you override equals
A common
source of bugs is the failure to override the hashCode method. You
must override hashCode in every class that overrides equals. Failure
to do so will result in a violation of the general contract for
Object.hashCode, which will prevent your class from functioning
properly in conjunction with all hash-based collections, including
HashMap, HashSet, and Hashtable.
I suggest you read that chapter. There are a lot of examples, that you can learn, what will happen if you don't do so.
It depends on the collection, most collections should work even if the hashCode of the elements has not been overridden, except collections like HashSet which rely on the element hashCode in order to work properly.
Beware that the hashCode of a collection usually relies on the hashCode of the elements:
Returns the hash code value for this collection. While the Collection
interface adds no stipulations to the general contract for the
Object.hashCode method, programmers should take note that any class
that overrides the Object.equals method must also override the
Object.hashCode method in order to satisfy the general contract for
the Object.hashCode method. In particular, c1.equals(c2) implies that
c1.hashCode()==c2.hashCode()
See: http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#hashCode%28%29
**type of field** **hash code formula**
boolean fieldHash = f ? 0 : 1
any integer type except long fieldHash = (int) f
long fieldHash = (int) (f ^ (f >>> 32))
float fieldHash = Float.floatToIntBits( f )
double int v=Double.doubleToLongBits(f)
fieldHash (int) (v ^ (v >>> 32))
any Object reference fieldHash = f.hashCode()
If you write a custom type you are responsible for creating a good hashCode implementation that will best represent the state of the current instance.
http://content.hccfl.edu/pollock/AJava/HashCode.htm

Categories