Techie
Techie

Reputation: 1651

adding a list of one type to a list of another type

I have my first list as

List<A> a

I have another list as

List<X.Y.Z> b

How do I add first list to the second one ?

I tried casting -

b.add(List<X.Y.Z>)a) - did not work

Tried adding through iteration of first list - did not work

definitely missed something ?

Upvotes: 0

Views: 3184

Answers (7)

Reimeus
Reimeus

Reputation: 159754

This is not possible as the reference types for both collections are different. The only way items from one List can be merged with those from another is if they both are of type List<Object> or the types themselves are identical (or at least derived from the same type).

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Consider the following case

    List<Integer> l1=new ArrayList<>();
    List<String> l2=new ArrayList<>();

    l1.add(2);
    l2.addAll((List<String>)l1);

you are trying to do the same thing. here you can't cast integer list to string list.

Same way you can't cast A type list to X.Y.Z. type.

Upvotes: 0

Barranka
Barranka

Reputation: 21047

Either you use List<Object>, to which you can add anything, or you write a method somewhere to convert an object of type A to X.Y.Z.

Notice that, if you use List<Object>, you'll need to cast the object to the desired class when you get it:

List<Object> myList = new List<Object>;
// ...
A myObject = (A) myList.get(0);
X.Y.Z otherObject = (X.Y.Z) myList.get(1);
// ...

Upvotes: 0

James Dunn
James Dunn

Reputation: 8274

It should also be noted that if you want to add the elements of List<A> a to List<X.Y.Z> b (which I assume is your intent), rather than the List<A> a itself as an element, you should use the addAll() method, not the add() method. But again, this won't work unless A is a subclass of X.Y.Z, and if A is a super class of X.Y.Z then casting the A variable will only work if it is an instance X.Y.Z.

Upvotes: 0

Shabbir Hussain
Shabbir Hussain

Reputation: 2720

You need to cast list a as the same type as list b so that they are the same type of object. Check out this article

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

The reason is because of type of List<>

X.Y.Z != A

You can use List<Object>, to which you can add() anything.Even though you added like that

you would have to cast each one back,while getting back.

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61512

Unless there is an Inheritance relationship between A and X.Y.Z you cannot have them in the same container because they are not of the same type

You can use the generic superclass Object as the type of the List and this will work.

Upvotes: 4

Related Questions