I'm thinking of implementing a 'container' with Java where I can store any type of objects, Integer, ArrayList, etc. When getting objects from the container, I will cast each result like this:
public void foo(int i开发者_开发问答) {
try {
Integer result = (Integer) container.get(i);
// do something with result
}
catch(...){..}
try {
Command result = (Command) container.get(i);
// do something with result
}
catch(...){..}
try {
ArrayList<MyClass> result = (ArrayList<MyClass>) container.get(i);
// do something with result
}
catch(...){..}
}
If it stores any type of objects mixed, use Object as storage class. All classes inherit from Object and for primitives use their respective wrapper classes. Or just use one of the bazillion container classes that already exist.
ArrayList <Object> container;
Also instead of using your try statements, think about instanceof
.
Whats your question?
But apart from that. Why are you trying to re-invent the wheel? Any of the Map collection classes will do exactly what you want. Check out HashMap.
精彩评论