如何在泛型中使用多个上界 [英] How to use multiple upper bounds in generics

查看:112
本文介绍了如何在泛型中使用多个上界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有泛型类型的Interface Foo -

  public interface Foo< T> {
boolean apply(T t);





$ b

有另一个实现这个接口的类Bar,但我想要的是泛型类型Bar应该是一个接口A和B类型的集合,用下面的定义给出编译器错误 -

  public class Bar implements FOO<收集和LT ;?扩展A& B>> {
@Override
public boolean apply(Collection< ;? extends A& B> collect){
...
}
}

您能否建议正确的方法来达到此目的?

我可以在方法级别使用多个边界吗?

解决方案

这不适用吗?

  public class Bar< T extends A& B个实现Foo< Collection< T>> {
@Override
public boolean apply(Collection< T> collect){
...
}
}


I have a Interface Foo which has a generic type -

 public interface Foo<T> {  
     boolean apply(T t);  
 }

Having another class Bar which implements this interface but what I want is the generic Type of Bar should be a Collection of type Interface A and B, With the below definition its giving compiler error -

public class Bar implements Foo<Collection<? extends A & B>>{
  @Override
  public boolean apply(Collection<? extends A & B> collect){
   ...
  }  
}

Can you suggest the correct way to achieve this?

I can use multiple bounds at method level only?

解决方案

Wouldn't this work?

public class Bar<T extends A & B> implements Foo<Collection<T>>{
  @Override
  public boolean apply(Collection<T> collect){
   ...
  }  
}

这篇关于如何在泛型中使用多个上界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆