代码出自《Thinking In Java》的练习,复制过来的,但是发现编译错误。
public static <T> Set<T> union(Set<T> a, Set<T> b) {
try {
if(a instanceof EnumSet) {
Set<T> result = ((EnumSet<T>)a).clone();
result.addAll(b);
return result;
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Set<T> result = new HashSet<T>(a);
result.addAll(b);
return result;
}
出错的一行是Set<T> result = ((EnumSet<T>)a).clone();
报的错误是:Type parameter 'T' is not within its bound,should extend 'java.lang.Enum<T>'
不明白为什么,估计是泛型哪里没理解,请教大家。
------解决方案--------------------
public static <T extends Enum<T>> Set<T> union(Set<T> a, Set<T> b) {
或者
Set<T> result = ((EnumSet)a).clone();