meghs karve wrote:...but the answer given there is that if hashcode method is overridden then duplicate values do not get printed and my answer should be 3 instead of 4???
Yes thats right, you're adding the same element having value "34" 2 times, but as it IS A Set, the object didn't accept the second element with value 34.
meghs karve wrote:that means i cant sort and remove duplicates in case if i put a Class in generics....It will only work for wrapper class objects???not user defined classes???
Just ignore what Neha Daga said. Of course you can use collections classed with your own classes. Just implement the hashCode and equals methods correctly.
My advice: use the @Override annotation. Then you'll get an compile-time error when your
not overriding something. What just happened.
Raju Champaklal wrote:ignore what Wouter has said....add method will give false if it sees that if two objects are meaningful equal
But in the add method hashCode and equals are used. So if you don't implement the hashCode and equals methods properly the method
will return true even though the set already contains an meaningful equal object.
i hope you are clear now
It's part of the java language. It's not bound to a certain compiler or IDE.
Raju Champaklal wrote:look if you use that notation then the compiler will help you find the error....this is good if you are building a project and you want to find the trivial errors fast....then i totally agree use that notation....but while preparing for scjp i think the better you get at finding out the errors the better...if i hadnt seen this question today i wouldnt have ever found that c in hashCode is capital...now in future i would make sure that C is capital....
The @Override is there for a reason:
Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
It is highly recommended that the @Override annotation be used when you are overriding the declaration or implementing the method from an interface (java 6).
In the example, being discussed here, the intention is to override the implementation of hashCode(). Irrespective of whether the example is for SCJP or for any project, it is right to use the @Override.