3

Say I have a class like this:

class ParameterizedType<T>{
    public boolean equals(Object o){
        if (ParameterizedType<T>.class.isInstance(o)){
            ParameterizedType<T> other = (ParameterizedType<T>) o;
            return this.toString() == other.toString();
        }
        return false;
    }
}

I can get two different warnings from eclipse in such a method.

  1. ParameterizedType<T>.class is not syntactically correct

  2. (ParameterizedType<T>) o is an unchecked cast

How could one get around this?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
wginsberg
  • 185
  • 2
  • 12
  • @kocko has the right information. To get around this you need to use `@SuppressWarnings("unchecked")`. Eclipse gives helpful hints when you hover over the warning. By putting this in you are telling yourself, and other developers, that yes I acknowledge that this is unchecked but I need to do it. – markbernard Jul 20 '15 at 14:26
  • Are you trying to implement equals by comparing string references? It's bad practice to calculate `equals` by referring to the `toString` method anyway, but comparing strings with `==` is a [serious mistake](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – RealSkeptic Jul 20 '15 at 14:26

1 Answers1

6
  1. ParameterizedType<T>.class is not syntactically correct

The reason for this is that with .class you're referring the .class value at Runtime and since Generics is a compile-time feature of Java and the type parameters get erased and replaced with actual type(s), then the statement doesn't make sense at Runtime and the <T> is completely redundant.

Note that the same rule applies for the instanceof operator (i.e. you can't do if (something instanceof SomeGenericClass<T>))

  1. (ParameterizedType<T>) o is an unchecked cast

There's no way to compare an Object to ParameterizedType unless downcasting. The IDE correctly suggests that the cast is unchecked, but in order to compare the instances, you have to downcast at some point. In this case, adding a @SuppressWarnings("unchecked") above the method would be fine.

Please also note that Strings in Java should not be compared with ==

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147