【发布时间】:2015-03-08 11:39:00
【问题描述】:
我有一个 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;
}
}
这是函数接口:
public interface Function<A, B> {
B apply(A value);
}
【问题讨论】: