How to convert java.lang.Object to ArrayList?

sjain picture sjain · Sep 8, 2011 · Viewed 137.6k times · Source

I have a valid ArrayList object in the form of java.lang.Object. I have to again convert the Object to an ArrayList. I tried this:

Object obj2 = from some source . . ;
ArrayList al1 = new ArrayList();
al1 = (ArrayList) obj2;
System.out.println("List2 Value: "+al1);

But it is printing null. How can I do this?

Answer

Lucas Pires picture Lucas Pires · Oct 16, 2018

You can create a static util method that converts any collection to a Java List

public static List<?> convertObjectToList(Object obj) {
    List<?> list = new ArrayList<>();
    if (obj.getClass().isArray()) {
        list = Arrays.asList((Object[])obj);
    } else if (obj instanceof Collection) {
        list = new ArrayList<>((Collection<?>)obj);
    }
    return list;
}

you can also mix the validation below:

public static boolean isCollection(Object obj) {
  return obj.getClass().isArray() || obj instanceof Collection;
}