Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<Object> to List<Dog> in Java [duplicate]

How to convert List to List. I tried doing this by

List<Object> obj = (some initialization)
List<Dog> dog =(List<Dog>)obj;  

So this throws an error

ERROR: Cannot cast from List<Object> to List<Dog>

Where

 List<Object> 

I get from the Hibernate Query

FROM DOG 
like image 496
Syed Hassan Avatar asked Jun 02 '26 17:06

Syed Hassan


2 Answers

Iterate over the List<Object> and cast every item explicitely

List<Dog> dog = new ArrayList<Dog>;
for (Object o : obj)
    dog.add((Dog) o);
like image 129
Parker_Halo Avatar answered Jun 06 '26 06:06

Parker_Halo


The cast works if you use a List<?> instead:

List<?> list = (some initialization);
List<Dog> dog = (List<Dog>)list;

If you got a List<Object> you still can cast it to a List<Dog>

List<Object> list = (some initialization);
List<Dog> dog = (List)list;

Of course this should only be done when you are sure that the list really contains Dog objects (e.g. as result value from your HQL query FROM Dog).

like image 26
wero Avatar answered Jun 06 '26 05:06

wero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!