我刚刚阅读了 Bloch 的 Effective Java,在泛型章节中有一节讨论了“身份函数”。
public interface UnaryFunction<T> {
T apply(T arg);
}
// Generic singleton factory pattern
private static UnaryFunction<Object> IDENTITY_FUNCTION = new UnaryFunction<Object>() {
public Object apply(Object arg) { return arg; }
};
// IDENTITY_FUNCTION is stateless and its type parameter is
// unbounded so it's safe to share one instance across all types.
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) IDENTITY_FUNCTION;
}
我已经读过“为什么禁止这个未经检查的警告是安全的?” 并且答案解释了未经检查的警告问题,但是当身份功能似乎与身份无关时,让我对“身份功能”的概念完全不满意。
Bloch 只是假设我知道它是什么,但在他用来说明它的实现中,它与一个或多个身份无关。
我在 wikipedia 上查看了它:Identity Function @ wikipedia,但它的纯理论描述也没有告诉我它与身份有什么关系。
我在谷歌上搜索,有些人将.equals()
and.hashCode()
方法称为身份函数,这有点道理,但当然它们的实现与 Bloch 的方法完全不同,它返回输入参数不变。这和身份有什么关系?
其他人将数据库函数称为身份函数,在每次调用时给出一个新的 ID,这也更有意义,但显然范围非常有限。