Steve
Steve

Reputation: 176

Override equals and cast object to string

EDIT: the question is why cant I use ".contains" (override .equals() in the object) to compare object attributes (a string) instead of comparing the object itself. Thanks JB: Turns out I was confusing overriding compareTo() with overriding equals()

EDIT: QUESTION REDEFINED:

Why cant I override equals to compare strings in my object:

public boolean equals(Object obj){
  ...
  if(obj instanceof String){
    String testString = (String) obj;
    ...
  }
  ...
}

Or even overload for that matter:

public boolean equals(String stringObj){
  ...  
}

I read somewhere that the compiler doesn't use logic to decide this, it uses types. So if I then call myObj.equals(stringOne + "_" + stringTwo) shouldn't this work as it knows a string is being passed? Thanks,
Steve.

Upvotes: 0

Views: 284

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

Why this code doesn't make sense:

  1. because Comparable is supposed to respect rules: if a < b is true, then b > a must be true. You can compare an instance of your class with String, but a String can't compare with an instance of your custom class. You're thus breaking the contract of Comparable
  2. because Vector doesn't use compareTo() to check if an element exists or not. It uses equals().
  3. Because you shouldn't alter the nature of a class just to implement a specific use-case consisting in adding instances of this class to a list and check for duplicates. This logic should be outside of the class. You could simply loop through the list and check is an instance with the item and position already exists or not, before creating your custom class instance.
  4. because you shouldn't use Vector for many years (since Java 2 - we're at Java 8). And since it seems the goal is to avoid duplicates, what you should use is a Set.

Do the right thing, and use a HashSet. Make sure CustomClass implements equals() and hashCode() correctly. You could also use a HashMap<CustomClassKey, CustomClass>, where CustomClassKey is a simple class containing the two fields identifying your CustomClass instances.

Upvotes: 1

Related Questions