当前位置: 代码迷 >> J2SE >> 这个代码为什么报错,该如何解决
  详细解决方案

这个代码为什么报错,该如何解决

热度:84   发布时间:2016-04-23 20:37:38.0
这个代码为什么报错
代码出自《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();
  相关解决方案