By using java reflection, we can easily know if an object is an array. What's the easiest way to tell if an object is a collection(Set,List,Map,Vector...)?
Java provides three different ways to find the type of an object at runtime like instanceof keyword, getClass(), and isInstance() method of java. lang. Class.
A Collection object is an ordered set of items that can be referred to as a unit.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
if (x instanceof Collection<?>){ } if (x instanceof Map<?,?>){ }
Update: there are two possible scenarios here:
You are determining if an object is a collection;
You are determining if a class is a collection.
The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection
or Map
will cover the Java Collections.
Solution 1:
public static boolean isCollection(Object ob) { return ob instanceof Collection || ob instanceof Map; }
Solution 2:
public static boolean isClassCollection(Class c) { return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c); }
(1) can also be implemented in terms of (2):
public static boolean isCollection(Object ob) { return ob != null && isClassCollection(ob.getClass()); }
I don't think the efficiency of either method will be greatly different from the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With