Genric cast from impl to interface

I have an interfaceABCInterface

and an implementationACBImpl

I want to write a method which will return a set of ABCImpl in form of ABCInterface, how can I do that using generics.

publicclass ABCHelper{

Set<ABCImpl> abcs =new HashSet<ABCImpl>();

public Set<ABCInterface > getABCs(){

return abcs;

}

}

the above program will give me a cannot cast error while compiling.

How to solve this problem.

TIA

Shajee

[791 byte] By [shajee.imrana] at [2007-11-27 4:52:47]
# 1

You wil have to return "Set<? extends ABCInterface>", as a Set<ABCImpl> is no Set<ABCInterface>.

Simple example:

interface Animal {}

class Dog implements Animal {}

class Cat implements Animal {}

Set<Dog> dogs = new HashSet<Dog>();

Set<Animal> animals = dogs; // BAD

animals.add(new Cat());

If the BAD line would be possible (which is similar to your getABCs()), you could add a Cat to the set of Dogs.

stefan.schulza at 2007-7-12 10:06:56 > top of Java-index,Core,Core APIs...
# 2

Define your set like this:Set<ABCInterface> abcs = new HashSet<ABCInterface>();

abcs.add(new ABCImpl()); // you can add ABCImpl instances in it

// ...

or rename you method like this:public Set<? extends ABCInterface> getABCs() {

// ...

}

Edit: man I'm slow...

prometheuzza at 2007-7-12 10:06:56 > top of Java-index,Core,Core APIs...
# 3
Thanks , I got it now.
shajee.imrana at 2007-7-12 10:06:56 > top of Java-index,Core,Core APIs...