Java For语句覆盖未知类型转换的列表

Java For语句覆盖未知类型转换的列表,java,generics,casting,Java,Generics,Casting,我试图在for循环中将对象列表中的每个元素自动转换为其正确的类型 class A { } class B { void sampleMethod() { List<?> l1 = //initialized somewhere; /* I do know perfectly l1 got elements of Class A I just could not declare List<A> for other (ge

我试图在for循环中将对象列表中的每个元素自动转换为其正确的类型

class A {

}

class B {
  void sampleMethod() {
    List<?> l1 = //initialized somewhere;
    /* 
       I do know perfectly l1 got elements of Class A
       I just could not declare List<A> for other (generic types) reasons
    */
    for (A el: l1) { // Type mismatch: cannot convert from element type capture#1-of ? to A
      System.out.println(el);
    }
  }
}
为什么我不能在for语句中进行这种铸造?真的没有办法做到干净吗?

如果以下是“我完全知道l1有A类元素”,那么试试:

List<?> l1 = ...

@SuppressWarnings("unchecked")
List<A> l2 = (List<A>) l1;

for (A a: l2) { ... }

在循环中使用铸造元素的解决方案是完全合适的<代码>列表是未知的列表,一个元素类型与任何内容匹配的集合。因此,您唯一可以确定的是,所有项目都是对象,您也是这样做的。这总是安全的,因为无论集合的实际类型如何,它都包含对象。您可以参考类似的案例,其中被认为是良好的代码示例

希望有帮助

真的没有办法做到干净吗

如果使用通配符声明
列表

List<?> l1 = //initialized somewhere;
List l1=//在某处初始化;
您永远无法在没有任何警告的情况下将其元素强制转换为特定类型。
你试图做的事违背了泛型的目的

你在评论中写道:

由于其他(泛型类型)原因,我无法声明
List


没有通配符或绑定的泛型变量(如
List
)有一些限制。它的一个已知特性是您不能为它分配
列表
,其中
B
A
的子类。但是有另一种方法可以让它像
列表那样工作。你为什么不能使用
列表呢?@ShanuGupta工作得很好!对我来说很有意义!非常感谢。
List<?> l1 = ...

@SuppressWarnings("unchecked")
List<A> l2 = (List<A>) l1;

for (A a: l2) { ... }
for (Object generic: l1) {
    if (generic instanceof A) {
        A a = (A) generic; // without warnings
        // do stuff
    } else if (generic == null) { // if nulls possible
        // do stuff
    } else {
        throw new IllegalArgumentException("item not of class A");
    }
}
List<?> l1 = //initialized somewhere;