• Post Reply Bookmark Topic Watch Topic
  • New Topic

Type mismatch with generics  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Me and generics have yet to make peace. For something that *seems* so simple, it has been battle after battle.

I'm trying to make a Comparator to help with a sorting task. Below is a hacked down version of the class which still gives the error.
I'm not understanding why it won't compile. The error message doesn't help, because to me it says "Error ...apple does not equal apple!"
I gave it <T extends String> after having problems with a simple <T>. I figured that it didn't have enough information so I added the constraint. ("extends String" means String or lower in inheritance right?) But still it will not compile if I try to use any String methods on what I believe to be a String. Other attempts just yielded "cannot find symbol" errors. String is in java.lang, so it must be able to find it right? Anyway, any help on this would be great.

Thanks,
Paul



TestComparator.java:7: error: incompatible types
T myVariable = o1.toString();
^
required: T
found: String
where T is a type-variable:
T extends String declared in class TestComparator
1 error
 
Sheriff
Posts: 22845
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's look at this code:

The toString() method returns a String. But T is some subclass of String. If you're going to assign an object to a variable of a subtype like that, you have to use a cast.

This is a basic rule of Java which has nothing at all to do with Generics. And Generics doesn't make that rule go away. Here's another example of the rule which you might understand more clearly:

String is a subclass of Object, you say, so why can't we do that assignment? Because the thing you assign to a String variable must be a String, or a subclass of String. Object won't do.

It's exactly the same with your Generics code, just obfuscated a bit.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that class String is final - it is not possible to subclass it. So declaring a type parameter "T extends String" doesn't really make sense - the only type T that can satisfy the restriction is class String itself. This means that you don't need the type parameter at all, you could just as well just use String instead of the type parameter T.
 
Paul Berry
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK guys thank you. I'll have to remember that even though something is obvious to me, the compiler may not have enough information to determine; or guarantee.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!