简体   繁体   中英

Java method cast Arraylist of childclass to parentclass and reverse

I have a Parent Class Item and multiple child classes itemA, itemB etc.

Now I want to have a method which takes 2 ArrayLists of the same classtype (for example itemA,itemA) and map the items based on a method in the parent class( so my idea was to make a method which takes in 2 Arraylists of the parent class so it accepts Arraylists of the child classes which were cast to the parent class.

Heres how the method should look like:

HashMap<Item,Item> mapping(ArrayList<Item> prop1, ArrayList<Item> prop2)
{
    //Content of the method not that important
}

And I should be able to call the method with the Arraylists of the child classes like

Arraylist<ItemA> list1 = ...;
ArrayList<ItemA> list2 = ...;
mapping(list1, list2);

But Apparently you cannot cast between Arraylists that easily. My only idea was to write 3 seperate methods for the 3 classes itemA, itemB, itemC. Does anyone have a better idea?

<T extends Item> HashMap<T,T> mapping(ArrayList<T> prop1, ArrayList<T> prop2)
{
    //Content of the method not that important
}

You need something like this:

<T extends Item> HashMap<T, T> mapping(ArrayList<T> prop1, 
                                       ArrayList<T> prop2) {
    // ...
}

then

Arraylist<ItemA> list1 = ...;
ArrayList<ItemA> list2 = ...;

HashMap<ItemA, ItemA> map = mapping(list1, list2);

Note that the type system will ensure that the same type ( ItemA , ItemB , whatever) is used for both the arguments and the result.


Apparently you cannot cast between Arraylists that easily.

Correct. There is no subtype relationship between ArrayList<Item> and ArrayList<ItemA> etcetera

My only idea was to write 3 separate methods for the 3 classes itemA, itemB, itemC.

The 3 methods would have to have different names or be in different classes. You will find that Java won't let you declare

HashMap<Item,Item> mapping(ArrayList<Item> prop1, 
                           ArrayList<Item> prop2)

and

HashMap<ItemA,ItemA> mapping(ArrayList<ItemA> prop1, 
                             ArrayList<ItemA> prop2)

in the same class / interface. Method signatures must be distinguishable after type erasure !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM