我在返回扩展某些内容的通用类型T的列表时遇到问题。
我有一个称为A的基类,以及2个子类B和C。我想从某个方法返回B的列表或C的列表,具体取决于某些上下文,但是我无法让编译器同意它。
我的意思是:
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<B> ls1 = new Main().method1();
List<C> ls2 = new Main().method2(); // Won't work,
// have to cast to it
// i.e. List<C> ls2 = (List<C>) new Main().method2();
System.out.println(ls1);
System.out.println(ls2);
}
<T extends A> List<T> method1() {
List<B> ls = new ArrayList<>();
ls.add(new B());
return ls; // Doesn't work now, compiler error
// works if I explicitly cast to it, but says
// unsafe or unchecked operation
// return (List<T>) ls;
}
List<? extends A> method2() {
List<C> ls = new ArrayList<>();
ls.add(new C());
return ls;
}
}
class A {
}
class B extends A {
}
class C extends A {
}
如您所见,我尝试了通配符和实际类型T,但是它们都没有摆脱编译器错误:“不兼容的类型”。
任何帮助将不胜感激,谢谢。
说列表包含类型B
的项目并允许类型的项目C
存在其中是危险的。可以肯定地说,该列表包含一个接口或超类。
这是一个引发运行时异常的危险示例。
import java.util.*;
public class Main {
public static class A {
public String getA() { return "A"; }
@Override public String toString() { return getA(); }
};
public static class B extends A {
public String getB() { return "B"; }
@Override public String toString() { return getB(); }
}
public static class C extends A {
public String getC() { return "C"; }
@Override public String toString() { return getC(); }
}
public static void main(String[] args) {
List<B> ls1 = new Main().method3();
List<C> ls2 = new Main().method3();
// Will work, because toString() for each class is handled by each class.
System.out.println(ls1);
System.out.println(ls2);
// Runtime errors!
ls1.stream().map(B::getB).forEach(System.out::println);
ls2.stream().map(C::getC).forEach(System.out::println);
}
public static <T extends A> List<T> method3() {
return Arrays.asList((T) new A(), (T) new B(), (T) new C());
}
}
列表的类型应该是一个共同的祖先,例如,List<A> ls1
以便您可以在遍历列表时安全地调用通用方法。
public static void main(String[] args) {
List<A> ls3 = new Main().method3();
ls3.stream().map(A::toString).forEach(System.out::println);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句