I have seen that one can use
ArrayList<Object> objectList = new ArrayList<Object>();
in order to generate a list that may contain different kinds of objects (such as object A and object B). I also have seen answers that state one can search what kind of objects are contained in that list by using
for (Object obj : objectList){
if(obj.getClass() == A.class){
doSomething();
}
}
However, its has been mentioned that this is not a very elegant approach. On the other hand, if I use an abstract class or an interface I need to have the same methods for object A and object B. For example if A.get() returns an integer, B.get() must also return an integer. But what I want is that the method making use of my objectList will do something different for different objects contained in the objectList. So A.get() may return an integer, B.get() may return a string.
So what I want to ask you guys is what is the best way to do this? Its not difficult to write a "hack", but I want to write good code.
Thanks.