Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple upper bounds in generics

Tags:

java

generics

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?

like image 902
Premraj Avatar asked Feb 17 '11 20:02

Premraj


People also ask

Can generics take multiple type parameters?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

How are bounds used with generics?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

Can a parameterized type have several bounds?

A type parameter can have multiple bounds.

What is upper bounded wildcards in generics?

Java generics upper bounded wildcard : Upper bounded wildcard is used to restrict the unknown type to be a specific type or a subtype of that type using '? ' with extends keyword.


1 Answers

Wouldn't this work?

public class Bar<T extends A & B> implements Foo<Collection<T>>{
  @Override
  public boolean apply(Collection<T> collect){
   ...
  }  
}
like image 146
KeithS Avatar answered Sep 23 '22 14:09

KeithS