Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java.lang.Object to ArrayList?

Tags:

java

java-6

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?

like image 674
sjain Avatar asked Sep 08 '11 11:09

sjain


People also ask

Can we convert object to ArrayList in Java?

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

How do you convert an object to a List of objects?

//Assuming that your object is a valid List object, you can use: Collections. singletonList(object) -- Returns an immutable list containing only the specified object. //Similarly, you can change the method in the map to convert to the datatype you need.

How do you convert an object to an array in Java?

To convert collection-based object into an array we can use toArray() or toArray(T[] a) method provided by the implementation of Collection interface such as java. util. ArrayList .


2 Answers

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;
}
like image 93
Lucas Pires Avatar answered Oct 08 '22 03:10

Lucas Pires


This only results in null if obj2 was already null before the cast, so your problem is earlier than you think. (Also, you need not construct a new ArrayList to initialize al1 if you're going to assign to it immediately. Just say ArrayList al1 = (ArrayList) obj2;.)

like image 15
Kilian Foth Avatar answered Oct 08 '22 03:10

Kilian Foth