Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

The "cost" in terms of performance will be practically zero (the only cost is in the runtime check on the downcast).

Casting doesn't change the list per se, just the type of the reference.

In what form (datatype) do you get the "data from the database"? If you expect to be able to convert from e.g. a JDBC ResultSet to a List, that's not going to work with a cast - you actually need to iterate through the ResultSet to get the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top