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.
"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.