相关疑难解决方法(0)

java从List <B>转换为List <A>,其中B扩展A

这可能吗?如果没有,为什么这不可能在Java?

interface B extends A {}
public List<B> getList();
List<A> = getList(); // Type mismatch: cannot convert from List<B> to List<A>
Run Code Online (Sandbox Code Playgroud)

我认为我正在寻找的主题是"协变类型",就像这里这里一样,但它的阴暗并且它并没有解决我的问题.

java types casting covariance

4
推荐指数
2
解决办法
801
查看次数

Java:使用接口指针转换为通用

在下面的示例代码的两个班EventA,并EventB都实现了interface Historical.Java可以自动转换一个EventAEventBHistorical当这些对象中的一个作为参数被传递,如在examineEvent下面的方法.但是,当引入泛型时,Java不再能够进行转换,即.from List<EventA>to List<Historical>- 除非findClosestValidEventIndex使用声明目标函数(在本例中)List<? extends Historical>.

有人可以解释为什么一定是这样吗?在我看来,泛型中接口的使用应该自动暗示<? extends Interface>.

public class SampleApplication {

   public interface Historical {
      public DateTime getDate();
   }   

   public static class EventA implements Historical {
      private DateTime date;
      @Override
      public DateTime getDate() {
         return date;
      }
   }

   public static class EventB implements Historical {
      private DateTime date;
      @Override
      public DateTime getDate() {
         return date; …
Run Code Online (Sandbox Code Playgroud)

java generics casting

2
推荐指数
1
解决办法
2475
查看次数

标签 统计

casting ×2

java ×2

covariance ×1

generics ×1

types ×1