Overriding “equals” method: how to figure out the type of the parameter?

前端 未结 9 1302
栀梦
栀梦 2021-02-05 07:47

I\'m trying to override equals method for a parameterized class.

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return t         


        
9条回答
  •  终归单人心
    2021-02-05 08:24

    I agree with the comments above, why does the class E need to be equal? and how do you want to treat subclasses of E?

    Anyway, given that here is a code sample that may help you:

    public class Example {
    
      T t;
    
      public Example(T t) {
        this.t = t;
      }
    
      public static void main(String[] args) {
        final String s = "string";
        final Integer i = 1;
        final Number n = 1;
    
        final Example exampleString = new Example(s);
        final Example exampleInteger = new Example(i);
        final Example exampleNumber = new Example(n);
    
        System.out.println("exampleString subclass "  + exampleString.t.getClass());
        System.out.println("exmapleIntger subclass " + exampleInteger.t.getClass());
        System.out.println("exmapleNumber subclass " + exampleNumber.t.getClass());
        System.out.println("Integer equals Number = " + 
            exampleInteger.t.equals(exampleNumber.t));
      }
    }
    

    You can call t.getClass() to get class information about the type of T (assuming it is not null, of course.)

    I hope this helps.

提交回复
热议问题