我有一个 Class
创建一个 ImmutableList
使用 generics 和 recursion 来提高性能,这是我无法理解的方法:
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
来自 E
至 E2
(或者,更确切地说,从 E
或 E
的父类(super class)型到 E2
或 E2
的子类型)。 Function
是一个接口(interface),只有一个名为 apply()
的方法. fn.apply()
接受类型为 E
的参数并返回 E2
类型的参数.
transform
将函数应用于执行它的列表的所有元素,因此它生成一个 ImmutableList<E2>
来自输入 ImmutableList<E>
它被执行。
<E2>
是一个通用类型参数,表示 transform
返回的列表中包含的元素的类型方法。
关于java - 这个通用函数的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28925963/