This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Defining Generics of subclassed objects?

 
Raymond Holguin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a situation that I can't seem to figured out.

ClassA
ClassB extends ClassA

I want to do the following but I cannot.

Set<ClassA> foo;
Set<ClassB> = Set<ClassA>;

I get
Type mismatch: cannot convert from java.util.Set<ClassA> to java.util.Set<ClassB>

I tried doing this and it works....but I cannot Iterate over the Set so its useless to me
Set<ClassA> foo;
Set<? extends ClassA> = Set<ClassA>;
Type mismatch: cannot convert from element type capture#3-of ? extends ClassA to ClassB

how can I accomplish this if possible?? im tryign to migrate an app from java 1.4 to java6 and this is road blocking me.

 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are trying to convert from the subclass to the superclass, that doesn't work in Java.

Change it to:
Set<ClassA> mySet = Set<ClassB>;

That doesn't work either as I just realized. Sorry.

Hunter
 
Raymond Holguin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your help, but after further review of the code i realized i misunderstood the situation. the problem is resolved now.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(It's good to follow up with the solution so that other readers, or people that land here via search result, know what the issue was.)
 
Raymond Holguin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes your correct, my apologies.

Turns out
Set<ClassA> foo;
Set<ClassB> = foo;

was never the situation...foo actually was Set<ClassB> the whole time.
Set<ClassB> foo;
Set<ClassB> = foo;

which is valid of course!!

I realized this after digging through the hibernate mapping for file this class. The reason why i got so confused in the place was because In the actual code ClassA and ClassB have the same name but different package locations AND you have 2 classes w/ the same name where one extend off the other LOL...thus i got confused which was which.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic