I was just wondering can a generic variable be reused. For example if I had a generic class that saves a database model supplied to it:
DataManager<ModelObject1> manager = new DataManager<ModelObject1>();
ModelObject1 object = new ModelObject1();
object.setSomeProperty();
manager.save(object);
Could I then reuse that same object to save a different type of model without creating a new generic variable. How could I do something like this:
manager = null;
manager = new DataManager<ModelObject2>();
ModelObject2 object2 = new ModelObject2();
object2.setSomeProperty();
manager.save(object2);
Due to type erasure, a
DataManager<ModelObject1>()is actually exactly the same as aDataManager<ModelObject2>()at creation time so from that perspective there is no reason why it should not be reused – after the correct casting.However, there are some caveats. If you modify the object to contain a reference to something that is specific to the defining class then things get complicated:
Something like this would mean you cannot re-use the object safely:
I would strongly recommend against it without a very good reason however. Perhaps if creating the manager is a very heavy process you could justify reusing them.
This code compiles fine but I would stongly recommend an
ss.clear()before the cast or anis.clear()after or you will end up with aSet<integer>containing aString: