开发者

Typecasting Elements in java.util.List

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开发者_StackOverflow社区 "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"?


If you "know" all the elements are cities you can do use type erasure. (This gives you a warning which you can turn off)

List<City> cityObjects = (List) baseCatalogObjects;

or you can pass the desired type to the search which can also check they are the right type.

List<City> cityObjects = getBaseCatalogObjects(City.class, CatalogType.CITY);

in fact you might find the CatalogType is redundant.

List<City> cityObjects = getBaseCatalogObjects(City.class);


As suggested by Peter you can change your method signature to something as follows,

public <T extends BaseCatalog> List<T> getBaseCatalogObjects(Class<T> clazz, CatalogType type){}

And then you can cast your list in the return statement like,

(List<T>) list;

Hope this helps!


You can try doing something like this:

City[] cityArr = baseCatalogObjects.toArray(new City[0]);
List<City> cityObjects = Arrays.asList(cityArr);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜