Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an Object is a Collection Type in Java?

Tags:

java

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...)?

like image 994
Sawyer Avatar asked Apr 16 '10 08:04

Sawyer


People also ask

How do you check what type an object is Java?

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.

Is object a collection?

A Collection object is an ordered set of items that can be referred to as a unit.

Is a collection an object Java?

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).


2 Answers

if (x instanceof Collection<?>){ }  if (x instanceof Map<?,?>){ } 
like image 141
Thilo Avatar answered Sep 17 '22 11:09

Thilo


Update: there are two possible scenarios here:

  1. You are determining if an object is a collection;

  2. 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.

like image 40
cletus Avatar answered Sep 17 '22 11:09

cletus