开发者

How to create a container of 'any' object

开发者 https://www.devze.com 2023-03-18 08:49 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号