Why doesn't the Java Vector's contains() method seem to call my custom equals() method?
-
I have a vector of custom objects which are created using a static inner class in my main application. However when I use the vector's contains method with a custom object it doesn't call the custom class's equals method. The equals method is as follows: Boolean equals(CustomObject b){ if( this.name.trim().equalsIgnoreCase(b.getName().trim()) ) return true; return false; }
-
Answer:
You are not overriding the equals method in the base Object class. Look carefully at the method signature.
Anonymous at Quora Visit the source
Other answers
Vector.contains() will call a method called Object.equals(Object) on your elements. Your method CustomObject.equals(CustomObject) does not override equals(Object), rather it overloads the 1-argument equals method signature. As such, it will not be called by any caller that is expecting to call an implementation of Object.equals(Object). You need to rewrite the method as an override. So: boolean equals(Object b) { return b instanceof CustomObject && name.trim().equalsIgnoreCase(((CustomObject )b).name.trim()) ); } Note also the use of the primitive boolean type as the return type - the return type of an overriding method must be a strict subclass of the return type of the overridden method and Boolean is not a strict subclass of boolean (since primitive types cannot be subclassed).
Jon Seymour
Related Q & A:
- Why doesn't ClickOnce in Visual Studio deploy content files from dependent assemblies?Best solution by Stack Overflow
- Why doesn't my PHP function work as expected?Best solution by Stack Overflow
- Why doesn't MySQL upload my data properly?Best solution by php-mysql-tutorial.com
- Why doesn't the messenger load?Best solution by Yahoo! Answers
- Why doesn't McDonald's sell hotdogs?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.