2

I am using generics in my class. MyObject must use T as an class, e.g. new MyObject(Long.class). In the method equal I want to ensure that the argument given to the method is an instance of T.

Object<T> is not a valid Java Source, I know. I added it to the code example to show you what I mean, i.e. that value is an instance of T.

But what is the correct way to implement the equal method??

public class MyObject<T extends Class> {

    public boolean equal(Object<T> value) {
        return true;
    }
}
1
  • Are you not overriding equals() (with an 's') Commented Oct 26, 2012 at 10:02

3 Answers 3

1

If you're overriding the equals() method, then you should check the class of the object being used to compare equality with.

  1. The signature will indicate that you can be passed any Object
  2. equality can be defined between different object types (doesn't often happen, but it's valid)

If you're not overriding equals(), I would change your method name to be distinct. Otherwise life is going to be very confusing.

Sign up to request clarification or add additional context in comments.

1 Comment

I recognized that naming the method "equal" wasnt a good idea. I do not want to override Object.equals()... My fault. Thx anyway :-)
0

Assuming that you're not out to override Object.equals(Object):

T extends Class makes scant sense because Class is final anyway, so the only thing T could be would be Class<U> for some U, and then you might as well let U be the type parameter. So what you might want it something like:

public class MyClass<T> {
  private Class<T> cl ;
  public MyClass(Class<T> cl) {
    this.cl = cl ;
    ...
  }
  public boolean equal(T value) {
    return true;
  }
}

and you then get to write, say, new MyClass<Long>(Long.class).

But are you sure you need to store the cl parameter at runtime at all? Normally you would leave it out completely, so you just write new MyClass<Long>().

1 Comment

Thats right. I used the type as generic and the class in the constructor... works fine. Thx
0

Assuming that you don't want to override equals. I think you should do below

public class MyObject<T> {

    public boolean isEquals(T obj) {
        return false;
    };
}

There is no need of Class in your case as you are passing Type to MyObject

    MyObject<Long> myObject = new MyObject<Long>();
    myObject.isEquals(Long.valueOf(10);//It will only allow Long
    myObject.isEquals(10);             //Fails for int

References

  1. Generic Types
  2. Lesson: Generics

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.