I have two classes named “BaseCatalog” and “City”. “BaseCatalog” is the parent class of “City”, in other words, “City” extends “BaseCatalog” class.
I have a method called “getBaseCatalogObjects” which takes one parameter catalogType and
returns a list of BaseCatalog objects. According to the given type, the type of the List may differ but it always contain objects that extends the main BaseCatalog class.
Because this method is a generic method, it always produces a List containing BaseCatalog objects. However in this case, I am sure each BaseCatalog instance in the list is also a City object:
List<BaseCatalog> baseCatalogObjects = getBaseCatalogObjects(CatalogType.CITY);
What I want to do is to convert this “baseCatalogObjects” list into a list called “cityObjects” which is something like:
List<City> cityObjects = (List<City>) baseCatalogObjects;
Is it possible or is there any efficient way to do such a conversion like this without creating a new java.util.List instance and iterating over the list “baseCatalogobjects”?
As suggested by Peter you can change your method signature to something as follows,
And then you can cast your list in the return statement like,
Hope this helps!