Is equals() and toHashCode affects vector add() remove() methods behaviour - java

As in the subject: Is equals() affects vector add() remove() methods behaviour.
I have got Vector<T> v;
1.Does the remove() method will work correct if I will not redefine equals() or hashCode() function in type T?
2.Does the add() method will work correct if I will not redefine equals() or hashCode() function in type T?

If you do not define an equals() for T, Vector.remove will use the default equals() implementation, which is object identity (==).
Vector.add() does not use equals(). It will happily add duplicates.
In either case, Vector does not use hashCode at all, so the implementation of hashCode (or lack thereof) will not affect the operation of Vector at all. However, if you redefine equals() for your element type, you must redefine hashCode() for other collection structures to work properly.
P.S. You should probably be using ArrayList instead of Vector. From the docs for Vector:
If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.
Even when a thread-safe implementation is needed, you are usually better off providing your own synchronization. The single-function-call synchronization offered by Vector is usually at the wrong granularity.

Related

Calling grandfather method

I'm writing a Java class that extends AbstractList because it has a lot of methods I want to inherit.
It has two methods I don't want to inherit: equals and hashCode. I would like to just call the default Object versions of those.
The syntax for calling an inherited method is e.g. super.hashCode() but that would just get the AbstractList version. What's the syntax for skipping over that and calling the grandfather version? Object.hashCode() doesn't work.
There isn't a way to access grandfather method implementations. On the other hand, you can use System.identityHashCode(this) and this == o to get the object-based equality behavior.
(Note, however, that it violates the List contract to use identity-based hash codes or equality for any type that implements the List interface.)

Why equals() is there is Comparator but not in Comparable interface in Java

equals() method is there in Comparator interface, but it is not present in Comparable interface. Why? Also, As per the contract between equals() and hashcode(), both must be overridden, it is not the case in Comparator. Why ? Can anyone help me to understand the concept behind it.
equals() method is there in Comparator interface, but it is not present in Comparable interface. Why?
Comparator.equals(...) is for testing if an object is equal to this comparator; it's not for testing whether two comparable objects are equals. (That's why it takes a single Object, not two T-s.) So just because Comparator declares it, doesn't mean there's any reason for Comparable to declare it.
That said, it's still worth asking why Comparator declares it, since Comparator (like every type) is already a subtype of Object. The reason for that is simply that Comparator wants to impose some extra requirements on equals(...), so it needs to supply specific Javadoc. (Specifically, it requires that two comparators never be considered equal unless they implement the same ordering. Implementations of Comparator can satisfy this requirement by just using the equals(...) from Object, or by defining a custom equals(...) that's more precise.)
Also, As per the contract between equals() and hashcode(), both must be overridden, it is not the case in Comparator.
Comparator doesn't actually "override" equals(...). Implementors of Comparator still inherit Object.equals(...), unless they override it.
Since Comparator is not providing an actual implementation of equals() — it just specifies some additional requirements — it doesn't need to say anything special about hashCode(). The general contract of hashCode(), and the relationship of hashCode() to equals(), still applies.
A class implementing Comparable already has an equals method inherited from Object, and Comparable imposes no extra constraints on equals().
Comparator requires that, for MyComparatorType.equals(Comparator other) to return true, both my comparator and the other comparator impose the same ordering. This allows for some performance improvements and optimizations, and will likely cause a runtime exception at some point down the line if this special contract is violated.
The relevant lines from the Comparator javadoc:
Indicates whether some other object is "equal to" this comparator. This method must obey the general contract of Object.equals(Object).
Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.
Note that it is always safe not to override Object.equals(Object). However, overriding this method may, in some cases, improve performance by allowing programs to determine that two distinct comparators impose the same order.
So Comparator should follow the same contract as any other thing implementing Object.equals(Object), which includes correct hashCode() behavior.
equals(Object obj) is present in all classes. It comes from Object class.
In Comparator interface, equals(Object obj) declaration is added to override the related javadoc in order that clients be aware of the interest to override equals() method for this class. It's a hint.
Javadoc of equals(Object obj) in Comparator :
Indicates whether some other object is "equal to" this comparator.
This method must obey the general contract of Object.equals(Object).
Additionally, this method can return true only if the specified object
is also a comparator and it imposes the same ordering as this
comparator. Thus, comp1.equals(comp2) implies that
sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every
object reference o1 and o2.
Note that it is always safe not to override Object.equals(Object).
However, overriding this method may, in some cases, improve
performance by allowing programs to determine that two distinct
comparators impose the same order.
What is the point ?
imagine you must call several times the Collections.sort() method with different comparators. If two comparators are equals() and you applied already one comparator, you should not apply the second comparator since it will have no effect. As said, it's a hint.
In Comparable, JDK developers don't judge useful to add any information about equals method overriding. Object's equals(Object obj) Javadoc should so be enough.

Effective Java: should I override equals() and hashCode() if the objects I'm creating are never compared with each other?

If the objects I create are not used for comparisons such as list.contains(new Employee("MM")), and also if those objects will only be stored in Lists returned from a database such as List<Employee>employeeList = employeeService.getEmployeeList(); then do I need to override equals() and hashCode() in Employee class?
No, you do not need to override .equals() and .hashCode() if you don't need a custom definition of equality. As long as you intend to treat every instance of your class as un-equal to other instances the defaults will work fine. You can store such objects in Lists and even in hash-based collections such as HashMaps and HashSets - both classes have no problems with the default Object notion of equivalence.
Furthermore for many classes you shouldn't override these methods. Many common design patterns will include classes that aren't intended to ever be equivalent, such as factories, singletons, and state machines. Defining a custom notion of equality for such classes can introduce strange bugs, or at a minimum simply be unnecessary boilerplate.
On the other hand value types, or classes intended specifically to be a structured representation of some sort of data should almost always override .equals() and .hashCode() (and possibly implement Comparable as well), because it's what users of these sort of classes are likely to expect. The Auto/Value project makes creating such value types really painless; if that's the type of class you're constructing I'd strongly encourage you to use it.
If you know you will never be using the object as a key in a HashMap or will never be putting it in any sort of Set, or never doing anything with it where you will do any object comparison other than "are these references referring to literally same instance or not", then you do not have to override equals() and hashCode().
And if that's not the case and you do have to override them, then do consider letting your IDE generate the overrides rather than doing it manually -- especially for hashCode(). And be aware that when having the IDE generate these, you can tell the IDE which fields to include and which fields not to include, which even further reduces any need to write the overrides manually.
As QuantumMechanic had said above, you do not need to override equals() and hashcode().
However, if the Employee class is going to be shared with other people, it's a good idea to add equal and hashcode so that it is easier for other people to use.
Also, Eclipse can generate these functions by right clicking -> Source -> Generate hashCode() and equals()
Good luck!
Why overriding Equals Method:
If you object needs to be stored on Collection i.e List, you should override equals method since when you will use indexOf, lastIndexOf etc API method as those api methods internally uses equals method. If you dont override equal method, then you might get those object back from collections since identity checking is not the right way to get the object back from Collections.
Why overriding hashCode Method:
If your object needs to be stored in a set or as key object in a map collection, you must override HashCode and Equals both becuase both methods are used to get the object back from those collections.

Do we need to override hashcode method?

I was looking at the java.lang.Object and also reading couple of questions in StackOverflow on the same topic.
equals() method is used to determine the equality of two objects.
Basically, if you want to store an object in a collection (Map, Set, List) then you have to implement equals and hashCode methods according to the contract defined in the documentation.
Correct me if i am wrong, If i am not storing my Class inside an collection, then i don't need to over-ride the hashcode method as the equals method would be more than enough.
This is correct. However, if you later (when the shortcut is long forgotten) put it into a Map or Set, things will crash badly.
It is recommended to override hashCode if you are overriding equals but it is not mandatory. This method is supported for the benefit of hash tables such as those provided by HashMap.
Note: So if you are sure that you or anyone else will never use your class object to be stored in a hashed collection then skip it. Otherwise override it.
If you don't put your object into HashMap or similar Collection / Map types then you don't to override the hashCode function in your class.
From Object#equals javadoc:
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.
This means, if you will override equals, then it will be good to also override hashCode to follow this contract, but it is not required.
Overriding hashCode() will help in a healthy categorization for all Hash based implementations in Java. The buckets will distributed depending on the hashCode() method's value.

Java hashCode() method override is not needed if we don't use hashmap or hashset

My co-worker was overriding the equals() method. My response was, have you also overridden the hashCode() method? His response was because we won't use hash map or hash set, it shouldn't really matter if we override hashCode(). Is that correct?
Yes he is factually right - however, if you need to put your objects in a hash-based collection one day, you will have to add hashcodes everywhere, which can be annoying + on that day you might implement your hashcode incorrectly (i.e. not consistent with equals) because you miss some subtlety in the equals method...
Considering that most IDEs provide an auto equals/hashcode generation feature, I see little reason not to create both.
Another way to look at it is: when you override a method from a parent class, you should follow the contract defined by that parent class. In the case of Object, the javadoc of equals is pretty clear:
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.
So unless you have a real design reason not to override hashcode, the default decision should be to follow the parent class contract and override neither or both.
If you override equals(), do override hashCode() as well. Even if you don't use hashCode() now, you or somebody else might use it.
For more on this topic, check the excellent SO answer
It's a code smell. Findbugs for example will warn you if you override either hashCode or equals without overriding the other. You should override both so that they are consistent with one another (that is, a.equals(b) => a.hashCode() == b.hashCode()).
A little effort now may save a lot of headaches later.
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.
Effective Java Item 9: Always override hashCode when you override equals.
If your class is a public class then you can not control how your classes will be used in future development. Without looking into source code (or through reflection) there is no way to know whether this class has overriden the hasCode method or not and the user will be surprised by the result if they use it in any hash based collections.
Actually assume that you create two different objects without overriding equals and hashCode methods. And then if you call equals method java calls hashCode method implicitly then checks the equality of hashcodes.
Overriding hashCode method is enough for checking equality of two objects. And it will be useful for future. You can use this class on collections.
Otherwise if you implement just equal method, it will solve just equality of two objects not more.
General:
only override those methods which you want to use in your own way and also those methods which are affected by this overriding.
Specific to your Ques:
From java docs,
Note that it is generally necessary to override the hashCode method
whenever equals() method is overridden, so as to maintain the general
contract for the hashCode method, which states that equal objects must
have equal hash codes.
Equals

Categories

Resources