Ive read a number of other questions on these pages about the class cast exception, and I want to be sure that my problem is essentialy the same thing (ie related to not knowing the bound type of the class during run time compared with during compile time).
so here is my test class....
public class testCastReturn{
public test(){
HashSet<String> StringHash; //a simple hash set
HashMap(<String, ComplexObject> ObjectInfo; //the String value is the name of the complexObject, and complexObject has multiple members (in this instance it is a java model for a database field so it has info pertaining to Key, size etc)
//create a ComplexObject here
addToObjectInfo(aComplexObject); // add it into the HashMap
//repeat above a number of times....
//now collect the 'names' of those objects
StringHash = getObjectKeys();
}
public void addToObjectInfo(complexObject c){
//put a complex object into the HashMap
ObjectInfo.put(c.getNameID, c); //create a set of key value pairs where the name of the object is the key to get the actual object
}
public HashSet<String> getObjectKeys(){
//retrieve the keys only
return HashSet<String> this.ObjectInfo.keySet(); //fails with classCastException
//this however works
HashSet<String> temp = new HashSet<String>(this.ObjectInfo.keySet());
return temp;
}
}//end class
If my understanding is correct this is why I can compile my code in either form, but I can only run the code where I explicity create a temp place to hold the keyset because as run time the JVM can't guarantee what the bound type of the keys are going to be in the ComplexObject. Please bear in mind that this is contrived version so may have oversimplified it, in my actuall code I am using a 'builder' and then passing the information to the 'finalised' class, and then a bunch of these classes are held within a third object that has the HashMap of ComplexObjects.
If you require any further info please ask (I can even send a copy of my library if you wish).
David