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

标签 java list generics syntax

我有一个 Class创建一个 ImmutableList使用 genericsrecursion 来提高性能,这是我无法理解的方法:

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));
    }

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

这是孔类:

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;
    }

}

这是函数接口(interface):

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

最佳答案

transform接受 Function来自 EE2 (或者,更确切地说,从 EE 的父类(super class)型到 E2E2 的子类型)。 Function是一个接口(interface),只有一个名为 apply() 的方法. fn.apply()接受类型为 E 的参数并返回 E2 类型的参数.

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

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

关于java - 这个通用函数的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28925963/

相关文章:

java - 如何以编程方式设置内容类型?获取 org.jvnet.mimepull.MIMEParsingException : Missing start boundary

java - 如何在grails中使用POST方法?

java - 如何在 Selenium IDE 中为 Web 目标选择正确的操作

python - 在列表上应用 boolean 值字符串

python - 将列表写入字典

c++ - 这个迭代器会出什么问题?

swift - 你能解释/解决这些 'generic constraint' 编译器错误吗?

java - 在 Java 中获取 Map<String, String[]> 的字符串表示的简单方法?

java - Wicket 中的 Form<Void> (或一般使用 Void 类型)

generics - “cannot borrow as mutable more than once”,即使是在放弃第一次借阅后