Cast object to arraylist in java

Cast Object to List String in Java

Cast Object to List String in Java | The Object class is the super class of all Java classes. Therefore it can hold all the types of objects in Java. Sometimes objects may hold a list of strings and to get those list of strings we need to cast the object.

The below program demonstrate how to cast the object to a list string in Java.

import java.util.ArrayList; import java.util.List; public class Main < public static void main(String[] args) < Listlist = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("CSS"); Object object = list; // cast object to list string List listString = (List) object; System.out.println(listString); System.out.println(listString.getClass().getName()); > >
[Java, Python, CSS]java.util.ArrayList

Note that if an object holds some other type of value instead of the list of strings then we can’t cast the object to list string. It will give java.lang.ClassCastException saying class java.lang.Object cannot be cast to class java.util.List.

Let us see an example for this where casting object to list string leads to java.lang.ClassCastException.

import java.util.List; public class Main < public static void main(String[] args) < Object object = new Object(); // cast object to list string ListlistString = (List) object; System.out.println(listString); System.out.println(listString.getClass().getName()); > >

It gives the following exception:-

Exception in thread “main” java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.util.List (java.lang.Object and java.util.List are in module java.base of loader ‘bootstrap’) at Main.main(Main.java:8)

Читайте также:  Return unreachable code java

In the below program object holds a set of strings, but not the list of strings. Therefore, the below program gives java.lang.ClassCastException exception.

import java.util.HashSet; import java.util.List; import java.util.Set; public class Main < public static void main(String[] args) < Setset = new HashSet<>(); set.add("Java"); set.add("Python"); set.add("CSS"); Object object = set; // cast object to list string List listString = (List) object; System.out.println(listString); System.out.println(listString.getClass().getName()); > >

It gives the following exception:-

Exception in thread “main” java.lang.ClassCastException: class java.util.HashSet cannot be cast to class java.util.List (java.util.HashSet and java.util.List are in module java.base of loader ‘bootstrap’) at Main.main(Main.java:14)

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

How to convert java.lang.Object to ArrayList?

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

If it is printing null you have a problem before this code is executed; hidden in the «from source . «

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

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

@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

11 Answers 11

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

public static 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)

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

 Object object = new Object(); // First way List objects1 = new ArrayList(); objects1.add(object); // second way List objects2 = Arrays.asList(object); // Third way List objects3 = Collections.singletonList(object); 

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

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

You can also do something like this:

 new ObjectMapper().convertValue(sourceObject, new TypeReference>() <>); 

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

Rather Cast It to an Object Array.

Object obj2 = from some source . . ; Object[] objects=(Object[])obj2; 

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.

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.

Converting from java.lang.Object directly to ArrayList 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_arraylist = Arrays.asList(t_array); 

You will still get Unchecked cast warnings.

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.

Источник

cast object to ArrayList

Note that there will be a lot of «else if» and not else< if()<>else<> > like it would be if you wrote this in python or something that cared about indentation and lines. I don’t think the actual outcome will differ though.

2 Answers 2

In Java generics are not reified, i.e. their generic type is not used when casting.

As that runtime cast won’t check your ArrayList contains Document objects, the compiler raises a warning.

I see . so any suggetions how to re-write the method? Should I make the method generic as well, will then work?

As long as you have to cast you will have the issue. You can either ignore the compiler warning or directly call setDocs(ArrayList) when you have the correct type.

No, that is not possible due to how generics are implemented in Java.

The type information is not available at runtime, so it cannot be checked by instanceof .

What you can do is cast to List and then check each element if it is a Document or not.

but I know, if its from type ArrayList, then it will be ArrayList. The compiler is giving me warning on the next row, where I cast to ArrayList

Best you can do is suppress the warning. And re-think if you really need this instanceof monster. In most programs, types should be known at compile time, without the need for this dynamic inspection.

yes I know, but the code is very old and compiles with Java 1.4, so I am trying to update it to Java 1.7 and wanted to clean up some basic warning like this. Thanks any way

Источник

Converting Object[] to ArrayList[] in Java

How can I create an Array of ArrayList if this doesn’t work? EDIT: To be shure everybody understands the problem. I need an Array that contains multiple ArrayLists. EDIT2: tableSize is an int.

Of course it throws an exception. An array is NOT a list, and an Object list is NOT a V class. In fact, what is V ? Is it a template parameter?

3 Answers 3

EDIT: OK, here is what you can do:

ArrayList[] table = new ArrayList[tableSize]; 

It compiles and works on Java 8 i’m using.

In case of Java you can not create new instance of array that type is generic.

T[] array = new T[size]; — cause compile error Cannot create a generic array of T .

The same error will be present when you will try to use it

ArrayList[] array = new ArrayList[size];

With the same reason. The Java runtime does not know what is T after compilation therefor will not be able to allocate valid memory space.

To pass this issue you have following options:

ArrayList[] array =new ArrayList[size];

Not the smoothest way to do it But if I got your question correctly something like this should do the trick:

int tableSize = 2; Collection listWithItems = new ArrayList<>(); listWithItems.add("Foo"); listWithItems.add("Bar"); Collection listOfList = new ArrayList<>(); listOfList.add(listWithItems); Object[] array = listOfList.toArray(new Object[tableSize]); System.out.println("Col: " + listOfList); System.out.println("Array: " + Arrays.toString(array)); 
Col: [[Foo, Bar]] Array: [[Foo, Bar], null] 

Short example without extra «fluff» to get the inital array:

Object[] theArrayOfLists = new ArrayList>().toArray(new Object[tableSize]); 

Источник

Оцените статью