I have the following DataSet class where we hold any kind of object. Mostly to transfer objects from the server to the client. The contents variable can hold any serializable object. It could be custom written class Objects or java classes like Integer, String etc.
I'm trying to convert this into generics. How should we go about converting this into Generics at the same time, I would like to make sure that I don't have to change all the containing object class code, since we are even using String and Integer classes within the contents.
I have simplified the class to only show some relevant fields and methods.
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Vector;
public class DataSet implements Serializable, PropertyChangeListener{
Hashtable contents = new Hashtable();
@Override
public void propertyChange(PropertyChangeEvent arg0) {
// TODO Auto-generated method stub
}
public void addObject(Object obj){
Vector vector = (Vector)contents.get(obj.getClass());
if (vector == null){
vector = new Vector();
vector.add(obj);
contents.put(obj.getClass(), vector);
}
}
public Vector getObjects(Class objType){
if (contents.contains(objType)){
return (Vector)contents.get(objType);
}
else{
return new Vector();
}
}
}
Appreciate your prompt replies. But, after reviewing the three answers below, I felt like I didn't convey the problem correct.
To make this the way I want, if I invoke dataset.getObjects(of E type), I should be getting a vector of E type. I shouldn't be casting into (Vector). Because I want the contents to be holding Class<E>, and Vector<E> of key value pairs. If we can do that, then only I could say that this is safe.
DataSet ds = new DataSet();
Vector<String> strings = ds.getObjects(String.class);
Vector<Integer> integer = ds.getObjects(Integer.class);
Vector<Employee> employees = ds.getObjects(Employee.class);