What is the correct way to convert generics in java?
interface A {
}
class B implements A {
}
class C {
public Set<B> returnSomeB(){
//some logic
}
}
C c = new C();
Set<A> = c.returnSomeB();
Set<A> = c.returnSomeB();
this line would give me a compile time error, what's the most proper way to seamlessly convert this since class B is a concrete class of A interface?
A variable of type Set<A>
can only hold a Set<A>
object, not a Set<B>
, even though B
is a subtype of A
.
The reason is this: What if you stored a Set<B>
object in a Set<A>
variable, then added an object of type A
(but not B
) to it? It would fit all the right argument types, but the end result would be a violation of Java's type safety.
To get around this, you can use wildcards. Instead of declaring a variable of type Set<A>
, declare one of type Set<? extends A>
Set<? extends A>
.
Try bounding your type parameter to the widest possible scope of acceptable values:
interface A {
}
interface B extends A {
}
class C {
public static void main(String[] args) {
final Set<A> foo = C.returnSomeB();
final Set<B> bar = C.returnSomeB();
}
public static <T extends A> Set<T> returnSomeB() {
return null;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.