I have a situation in which I am getting data from database, and I want to upcast it to ArrayList of objects
and then downcast it to different custom ArrayList i.e. List<User>
, List<Groups>
etc.
My question is up-casting to object and then down-casting to ArrayList, what will be the cost, and is it efficient or good practice.
EDITED
Instead of getting data as List<User>, List<Groups>
etc I want to get data as ArrayList<objetcs>
once and then as per my need, I will downcast data to ArrayList<User>,
ArrayList<Groups>
later on.
In Upcasting, we assign a parent class reference object to the child class. In Java, we cannot assign a parent class reference object to the child class, but if we perform downcasting, we will not get any compile-time error. However, when we run it, it throws the "ClassCastException".
Upcasting permits an object of a subclass type to be treated as an object of any superclass type. Basically, it's where you cast a subclass instance to one of its superclasses, to show an example in pseudocode.
In java, upcasting is not necessary as it's done automatically. And it's usually referred as implicit casting.
"Down casting" isn't a good idea as you shouldn't need to use any ArrayList specific methods. You should be able to use List
for every thing. The only public methods ArrayList provides which are not in List are ensureCapacity
(which isn't as useful as it looks) and trimToSize
which is rarely useful.
In terms of cost, it depends on whether you are likely to fail to down cast. If you are not throwing exceptions, a typical type check might take ~ 40 nano-seconds. Upcast should be optimised away by the JIT.
If the database doesn't actually return an ArrayList
, casting will not convert it for you -- instead you will see a ClassCastException
at runtime. You should instead instantiate a new collection of the type you would like to use and invoke its addAll(Collection c)
method on the collection returned from the database.
If you start with an ArrayList<Object>
, casting this to ArrayList
is not an upcast: it just casts a parameterized type to its raw counterpart. Furthermore, casting ArrayList
to ArrayList<String>
is not a downcast, either: it is an unchecked cast into a parameterized type. Both are compiler artifacts only and have no runtime equivalent.
If you are getting/saving
different tables from database
then for each table
first create classes for each table
with full mapping of table
. Then in the functions of (Insert,update,delete,select) pass data with respective table class objects. and use as it is. For this you have to create different function to get or save data to table. But it is the most efficient way of doing this task. For more information about upcasting/downcasting see the link here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With