【问题标题】:what dose this generic function do?这个通用函数有什么作用?
【发布时间】:2015-03-08 11:39:00
【问题描述】:

我有一个 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));
    }

这种语法对我来说是新的,&lt;E2&gt; 后面的 public 是什么意思? 这个参数意味着什么? Function&lt;? super E, ? extends E2&gt; 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;
    }

}

这是函数接口:

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

【问题讨论】:

    标签: java list generics syntax


    【解决方案1】:

    transform 接受从 EE2Function(或者,更准确地说,从 EE 的超类型到 E2E2)。 Function 是一个接口,只有一个名为apply() 的方法。 fn.apply() 接受E 类型的参数并返回E2 类型的参数。

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

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

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2011-11-18
      • 2013-10-21
      相关资源
      最近更新 更多