Java-通用类型未找到?

时间:2015-04-09 02:29:00

标签: java generics interface

我正在为家庭作业编写代码并且我收到此错误

GenericSet.java:101: error: method map in class GenericSet<T> cannot be applied
to given types;
            E ans = map(item);
                    ^
  required: LMap<T,E>
  found: T
  reason: cannot infer type-variable(s) E
    (argument mismatch; T cannot be converted to LMap<T,E>)
  where T,E are type-variables:
    T extends Object declared in class GenericSet
    E extends Object declared in method <E>map(LMap<T,E>)
Note: GenericSet.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

根据我的理解,我给出的接口传递了一个函数,我必须使用通用输入(T)来获得一个通用输出(E),它将存储在一个新的自定义中我制作的通用对象。它看起来很好但不是E.你能告诉我我做错了吗?

这是我的代码:

public <E> ExtendedSet<E> map(LMap<T, E> map) {
        GenericSet<E> finalVal = new GenericSet();
        for (T item: this.myList) {
            E ans = map(item);
            finalVal.addThis(ans);
        }
        return finalVal;
    }

注意:对象GenericSet实现了ExtendedSet 注2:实现的接口方法如下所示:

@FunctionalInterface
public interface LMap<T, E> {
    /**
      *Maps an element of type T to type E
      *@param element the source element to map from
      *@return E the destination element to map to
      */
    E map(T element);
}

1 个答案:

答案 0 :(得分:1)

您想要使用

E ans = map.map(item);

仍然需要通过实例调用功能接口的方法。通过省略该实例,您需要调用this.map(item),这需要LMap<T, E>