• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cannot assign generic object reference to similar type.  RSS feed

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code:



Can someone explain why "this.mainEntity = mainEntity" is incorrect and also show me the correct way to achieve this?

The error I am getting is "Type mismatch: cannot convert T to T"
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bob,
I'm a bit confused about what you are trying to accomplish. T appears to mean two things in your code. it's a type parameter for the whole class. It's also a type parameter that is further constrained for the method.

Can you elaborate in English about what you want each T to represent? That way we can comment on how the code relates to that.
 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well T can be any object that is a subclass of the class "Entities" so in my case it represents an object that can undergo the process of "collision." (I guess I should have put <T extends Entities> for "public class CollisionManager" since this class will only work with classes derived from Entities). Ultimately I need the "mainEntity" parameter to be visible to all of my methods so I can perform certain checks. But as you know my attempt to do this: "this.mainEntity = mainEntitiy" fails.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because you are confusing poor Java by using T in two different ways . Seriously though, if I give that restriction up front, I can use the class' opinion of T without having to use <T> in the method. <T> is meant for static methods and the like where the class doesn't have a type parameter.

 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't know that. Thank-you!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!