H Melua wrote:
I have a question please (just for the sake of understanding!)... Suppose that I have an ArrayList that holds any type of object... and that I will not know in advance what sort of objects it holds,
How can I automate the code below? Notice that I put "???" in the code because I don't know what the class is! Is there a way to find out automatically what the class is?
I know that Object.getClass() will return the class... but I don't know how to use it to make the code automatic!
At the moment there is no reason why I want to do something like this... I just want to understand how things work...
... I appreciate your patience!
I think that you are looking at it wrong...
The purpose of the instanceof isn't to handle many different types -- actually, maybe it is, but it is from the code point of view. There is something in the "if" condition block that requires that the instanceof condition be passed to enabled it to work.
So, the question is NOT ...
"Suppose that I have an ArrayList that holds any type of object... and that I will not know in advance what sort of objects it holds", how to deal with it with instanceof?
But the question should be ...
"Suppose that I have an ridiculous amount of code that is needed in handling all different types of objects" ... and quite frankly, if you need an endless amount of code, it is not the instanceof that is an issue.
Henry