Generics / Design help

Hey, firstly I don’t think this is possible. If it isn’t, can anyone recommend a better way of doing it?

I have an abstract class with one field that lots of other classes extend, each having different implementations of some abstract methods:


public abstract class Data
{	
	private DataType dataType;
        public abstract void ...();
        ...
}

DataType is an enum saying what type of data each instance is.

I have a map:

Map<DataType, Set<Data>> allData = new HashMap<DataType, Set<Data>>();

but when i get a value out of the map,

Set<Data> set = allData.get(DataType.X);

I would then have to cast each object inside set to DataX (if that is what the class is called that corresponds with DataType.X)


for (Data d: set)
{
      DataX dx = (DataX) d; //There is no chance that d won't be of type DataX
      //do something with dx here...
}

But I know that all the elements inside of set are of type DataX.

Is there any way I can make it so when I get a set out of allData, I can get a set of DataX?

Set<DataX> set = allData.get(DataType.X);

Thanks,
roland

when the language is make something really hard for you, you are probably on a wrong way.
Think of another way to story your data or try to explain to us in a wider way what you want to achieve

I don’t really know what you want to achieve with this but it looks like you rebuild the whole typing-system.

Instead of making the type of the Data object an instance variable why don’t you just create a Class DataX that extends the Data-class? Then you don’t have to worry what the type your Data-object is because Java will know the dynamic type of this object and will call the appropriate methods?