It is possible, I know, but is it "good code" to allow the .equals() function to return true when the objects are of different types? I'm not talking about an inheritance relationship, I mean completely different types. Here's an example:
public class Customer { //extends Object String customerID; //unique identifier . . .
public boolean equals(Object o) { if (o instanceof Class) { Class class = (Class)o; return this.customerID.equals(class.customerID); } else if (o instance of String) { return this.customerID.equals((String)o); } } }
I like this implementation, because now, if I have an ArrayList of Customer objects, I can get one by saying:
String id = "1234"; Customer bob = (Customer)customerList.get(customerList.indexOf(id));
This should work. And I think it makes for very clean/eleant code. But a String is NOT a Customer.
So what do you think? Is this OK, or the kind of thing that leads to confusion and bad hacks in the future...
This is not a good idea at all. It is worse than just a bad hack. What you are trying to do prevents the equals() method from functioning in the correct way and could therefore cause all sorts of problems.
The problem is that if two objects (a and b) are equal, then both of the following statements must return true: a.equals(b) and b.equals(a)
However the way you have designed your class this requirement fails.
For example if 'a' is an instance of Customer and 'b' is an instance of a String, then: a.equals(b) can return true, but since String has its own equals method b.equals(a) will fail.
You might suggest that you could inherit a new class from String and override the equals method in the new class, but this will not work because String is a final class and final classes can not be used in inheritance.
There are probably other reasons why this is a bad idea, but the one I have listed above is a biggie.
I think the solution to your problem is to use the java.util.HashMap class. Look in the Java API for more information.