47

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?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
sjain
  • 1,635
  • 9
  • 25
  • 35
  • 2
    If it is printing null you have a problem before this code is executed; hidden in the "from source ..." – Captain Giraffe Sep 08 '11 at 11:41
  • what the error you are getting, to me its working fine. Also give more details, Object obj2 = from some source . . ; for above obj2 what you are assiging – developer Sep 08 '11 at 11:47
  • below is the code i tried, its working fine.ArrayList al11 = new ArrayList(); al11.add("a"); al11.add("b"); Object obj2 =al11; ArrayList al1 = new ArrayList(); al1 = (ArrayList) obj2; System.out.println("List2 Value: "+al1); – developer Sep 08 '11 at 11:47
  • @Damodar Your second comment worked fine for me too. But my hidden method returns an String in form of Object, because of that i am getting following exception: Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList – sjain Sep 08 '11 at 12:04
  • [Answer updated for java 8+](https://stackoverflow.com/a/69454694/8430155) – Harshal Parekh Oct 05 '21 at 17:15

11 Answers11

40

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;
}
Lucas Pires
  • 1,281
  • 14
  • 21
15

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

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
10
    Object object = new Object();

    // First way
    List objects1 = new ArrayList<Object>();
    objects1.add(object);

    // second way
    List<Object> objects2 = Arrays.asList(object);

    // Third way
    List<Object> objects3 = Collections.singletonList(object);
Dharman
  • 30,962
  • 25
  • 85
  • 135
dimuthu
  • 865
  • 11
  • 15
9

Answer from 2021 (Java 8+)

Assuming that your object is a valid List object and if you want it in a specific datatype, use Stream.of(object):

Object o = Arrays.asList(1, 2);
((List<Object>) o).stream().map(String::valueOf).forEach(System.out::println);

Similarly, you can change the method in the map to convert to the datatype you need.


Note: This will lead to Type safety: Unchecked cast. This happens because the cast is a runtime check and the type has been erased when you receive it from some source. You can use @SuppressWarnings("unchecked") and live with it.


This could be a good article on this topic: Reified Generics for Java

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
  • The solution didn't work for me. See the object is a list (and not array), so `Stream.of` will return one single element. Example `Object list = Arrays.asList(1, 2); Stream.of(list).forEach(System.out::println); => `actual result `[1, 2]`, expected result `1\n2` – Soheil Pourbafrani Jul 11 '22 at 10:57
5

You can also do something like this:

  new ObjectMapper().convertValue(sourceObject, new TypeReference<List<YourTargetClass>>() {});
2

To convert the object to an immutable list of strings, no matter if it is a String or a collection of String, I used the following method:

public static List<String> convertObjectToListOfStrings(Object obj) {
    return obj == null ? null : (obj instanceof String ? List.of((String) obj)
            : (obj.getClass().isArray() ? Arrays.asList((Object[])obj)
                    : (obj instanceof Collection ? ((Collection<?>) obj) : List.of()))
            .stream().map(String::valueOf).toList());
}

Note: This code was elaborated by combining two of the answers already posted: https://stackoverflow.com/a/52839327/5538923 and https://stackoverflow.com/a/69454694/5538923 .

marcor92
  • 417
  • 5
  • 13
1

Rather Cast It to an Object Array.

Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;
vinay
  • 1,121
  • 2
  • 12
  • 17
1

An interesting note: it appears that attempting to cast from an object to a list on the JavaFX Application thread always results in a ClassCastException.

I had the same issue as you, and no answer helped. After playing around for a while, the only thing I could narrow it down to was the thread. Running the code to cast on any other thread other than the UI thread succeeds as expected, and as the other answers in this section suggest.

Thus, be careful that your source isn't running on the JavaFX application thread.

0

The conversion fails (java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList) because you have surely some objects that are not ArrayList. verify the types of your different objects.

khadre
  • 73
  • 1
  • 1
  • 6
0

Converting from java.lang.Object directly to ArrayList<T> which has elements of T is not recommended as it can lead to casting Exceptions. The recommended way is to first convert to a primitive array of T and then use Arrays.asList(T[]) One of the ways how you get entity from a java javax.ws.rs.core.Response is as follows -

    T[] t_array = response.readEntity(object);
    ArrayList<T> t_arraylist = Arrays.asList(t_array);

You will still get Unchecked cast warnings.

QuickSilver
  • 3,915
  • 2
  • 13
  • 29
ARK
  • 3,734
  • 3
  • 26
  • 29
0

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

Daham Akalanka
  • 295
  • 1
  • 10