How does instanceof work exactly? When I have a hierarchy of objects that extend and implement eachother, does being instance of something work through these both lines?
For example I want to know if my object is instance of Listor ArrayList or Collection?
I examined this tree, http://docs.oracle.com/javase/6/docs/api/java/util/package-tree.html
And they seem to fall all under Object ofcourse, but what I need, I think is AbstractCollection or even normal Collection , because that seems to be the highest in hierarchy.
Will I be fine, when I check an object against only Collection to cover all those 3 classes?
Yes,
instanceof Collectionwill return true for all implementation (direct or indirect) of the Collection interface.In the rare case that you do not want this, you’d have to use reflection. For example, Class#getDeclaredClasses will give you a list of all classes and interfaces that are directly extended/implemented by the class.
Once you know that something is a Collection, you can cast it to get access to its methods (like
iterator):