这个通用函数的作用是什么?

what dose this generic function do?

我有一个 Class 来创建一个 ImmutableList 使用 泛型 递归 来提高性能一种我无法理解的方法:

public <E2> ImmutableList<E2> transform(Function<? super E, ? extends E2> fn) {
        return tail == null
            ? new ImmutableList<E2>()
            : new ImmutableList<E2>(fn.apply(head), tail.transform(fn));
    }

这个语法对我来说是新的,public 之后的 <E2> 有什么用? 这个参数意味着什么? Function<? super E, ? extends E2> fn

这是洞 class :

public final class ImmutableList<E> {

    public final E head;
    public final ImmutableList<E> tail;

    public ImmutableList() {
        this.head = null;
        this.tail = null;
    }

    private ImmutableList(E head, ImmutableList<E> tail) {
        this.head = head;
        this.tail = tail;
    }

    public ImmutableList<E> prepend(E element) {
        return new ImmutableList<E>(element, this);
    }

    public <E2> ImmutableList<E2> transform(Function<? super E, ? extends E2> fn) {
        return tail == null
            ? new ImmutableList<E2>()
            : new ImmutableList<E2>(fn.apply(head), tail.transform(fn));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((head == null) ? 0 : head.hashCode());
        result = prime * result + ((tail == null) ? 0 : tail.hashCode());
        return result;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof ImmutableList))
            return false;
        ImmutableList other = (ImmutableList) obj;
        if (head == null) {
            if (other.head != null)
                return false;
        } else if (!head.equals(other.head))
            return false;
        if (tail == null) {
            if (other.tail != null)
                return false;
        } else if (!tail.equals(other.tail))
            return false;
        return true;
    }

}

这是功能界面:

public interface Function<A, B> {
    B apply(A value);
}

transform 接受从 EE2Function (或者,更准确地说,从 EEE2E2 的子类型)。 Function 是一个接口,只有一个名为 apply() 的方法。 fn.apply() 接受 E 类型的参数,returns 接受 E2.

类型的参数

transform 将函数应用于执行它的列表的所有元素,因此它从执行它的输入 ImmutableList<E> 生成一个 ImmutableList<E2>

<E2> 是一个泛型类型参数,表示 transform 方法返回的列表中包含的元素的类型。