【问题标题】:How to cast generics in a loop?如何在循环中强制转换泛型?
【发布时间】:2011-01-21 08:51:27
【问题描述】:
public static void someMethod(List < ? extends BaseDto > list) {
    for (ChildDto dto : list) {

    }
}

ChildDto 扩展了 BaseDto,在这里我确定它的列表中充满了 ChildDto。

我知道我可以做这样的事情

for (TextApplicationDto dto : (List<TextApplicationDto>)list) {

但它看起来并不漂亮。

有没有更好的铸造方法?

【问题讨论】:

  • 在我看来,它不漂亮是有好处的——你应该避免强制转换,因为它们会使你的代码不那么安全。当演员表看起来很丑时,您就不太愿意使用它。
  • 恕我直言,你不应该这样投。这样的演员阵容产生警告是有充分理由的。像 gabuzo 建议的那样做对我来说看起来好多了。

标签: java generics casting coding-style


【解决方案1】:

我认为最好的方法是:

public static void someMethod(List < ? extends BaseDto > list) {
    for (BaseDto dto : list) {
        ChildDto taDTO = (ChildDto)dto;
        // Whatever
    }
}

它还允许您使用instanceof 来确保列表只包含ChildDto

【讨论】:

    【解决方案2】:

    ChildDto 扩展了BaseDto,我敢肯定它的列表中充满了ChildDto。

    那为什么那个方法的参数类型不代表那个知识呢?

    应该是List&lt;ChildDto&gt;,甚至是List&lt;? extends ChildDto&gt;。

    您转换它的方式是一种解决方案,您也可以单独转换每个返回值。两者都同样“好”,因为它们会在大致相同的位置失败:

    for (BaseDto bDto : list) 7
      ChildDto dto = (ChildDto) bDto;
      // ...
    }
    

    【讨论】:

    • 因为我必须通过 List 我会得到编译错误,说它不能转换 List 扩展到 List 。我想处理那个班级的演员表。它不像 List 始终是 ChildDto 的列表,但在此方法中始终是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2014-02-04
    相关资源
    最近更新 更多