我有我的第一个清单
List<A> a
我有另一个清单
List<X.Y.Z> b
如何将第一个列表添加到第二个列表?
我试过铸造 -
b.add(List<X.Y.Z>)a) - did not work
尝试通过第一个列表的迭代添加 - 不起作用
肯定错过了什么?
我有我的第一个清单
List<A> a
我有另一个清单
List<X.Y.Z> b
如何将第一个列表添加到第二个列表?
我试过铸造 -
b.add(List<X.Y.Z>)a) - did not work
尝试通过第一个列表的迭代添加 - 不起作用
肯定错过了什么?
除非两者之间存在继承关系,否则A您X.Y.Z不能将它们放在同一个容器中,因为它们的类型不同
您可以使用通用超类 Object 作为 the 的类型,List这将起作用。
这是不可能的,因为两个集合的引用类型不同。一个项目可以与另一个项目合并的唯一方法List是它们都是类型List<Object>或类型本身相同(或至少从相同类型派生)。
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.
您需要将列表 a 转换为与列表 b 相同的类型,以便它们是相同类型的对象。看看这篇文章
type原因是由于List<>
X.Y.Z != A
你可以使用List<Object>,你可以使用add()任何东西。即使你这样添加
你必须在回来的时候把每一个都扔回去。
您可以使用List<Object>,您可以添加任何东西,或者您在某处编写一个方法来将类型的对象转换A为X.Y.Z.
请注意,如果使用List<Object>,则需要在获取对象时将其强制转换为所需的类:
List<Object> myList = new List<Object>;
// ...
A myObject = (A) myList.get(0);
X.Y.Z otherObject = (X.Y.Z) myList.get(1);
// ...
考虑以下情况
List<Integer> l1=new ArrayList<>();
List<String> l2=new ArrayList<>();
l1.add(2);
l2.addAll((List<String>)l1);
你正在尝试做同样的事情。在这里你不能将整数列表转换为字符串列表。
同样,您不能将 A 类型列表转换为 XYZ 类型。