Reputation: 269
Is it possible to compare 2 object from 2 different classes.
lets say i have an vector which adds all the objects from class A. i want to compare some string to the elements of the vector.
Example:
if(string.equals(vector.get(i)))
is this possible ?
Upvotes: 0
Views: 2367
Reputation: 500207
Yes, you can call equals()
. However, any reasonable implementation of SomeClass.equals()
would return false
if the argument is of a different class (other than perhaps a subclass).
If string
is an instance of java.lang.String
, this behaviour is specifically guaranteed:
The result is
true
if and only if the argument is notnull
and is aString
object that represents the same sequence of characters as this object.
Upvotes: 3
Reputation: 5689
It's perfectly valid to write something like;
public class MyClass {
public boolean equals(Object o) {
if(o instanceof SomeUnrelatedClass) return true;
return false;
}
}
But it is not advisable, as least I would try to avoid it. It would make handling MyClass
objects a little strange, for example putting them into a hash-based collection.
Upvotes: 0
Reputation: 10411
If the list's elements have type other than String it will always return false. From the String
documentation for method equals
:
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
This is generally true for the method equals - it will or should return true only in the eventuality that the compared object is of the same class or a subclass of the former.
Upvotes: 0
Reputation: 444
Equals method of an object can take any other object. However, it would be up to the implementation to not return true when comparing an apple with an orange
Upvotes: 0
Reputation: 61
Your objects are at least in the class Object, and thus (at least partly) in the same class.
Upvotes: 1