• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Generics problem

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Imagine this:

class ConcreteClass extends AbstractClass

public class Main {

public void doVector(Vector<AbstractClass> vector) {
for (AbstractClass ob : vector) {
// do Something
}
}

public Main() {
}

public static void main(String[] args) {
Main main = new Main();

Vector<ConcreteClass> vector = new Vector();
vector.add(new ConcreteClass());
main.doVector(vector);
}
}

This won't compile because vector is Vector<ConcreteClass> not Vector<AbstractClass>
even though ConcreteClass is a subclass of AbstractClass

I can get past this by casting vector to a simple untyped Vector,
although the compiler b!tches about unchecked conversions.

Alternatively I could declare my vectors as Vector<AbstractClass>
but in my application I actually have multiple different Concrete classes so that doesn't help.

Is there another solution that I'm missing?
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you tried something like



?

This wouldn't allow you to add to the Vector, but you could iterate through it.
 
Dave Tong
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's exactly what I needed. Completely brilliant. Thanks!
 
Quick! Before anybody notices! Cover it up with this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic