identity 方法是做什么的,Generic Singleton java
What does identity method do, Generic Singleton java
阅读有效java第 5 章第 27 项
它讨论了通用单例模式:
Now suppose that you want to provide an identity function. It would be
wasteful to create a new one each time it’s required, as it’s
stateless. If generics were reified, you would need one identity
function per type, but since they’re erased you need only a generic
singleton. Here’s how it looks:
public class GenericSingleton<T> {
private static UnaryFunction<Object> IDENTIFY_FUNCTION = new UnaryFunction<Object>() {
@Override
public Object apply(Object args) {
return args;
}
};
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) IDENTITY_FUNCTION;
}
public static void main(String[] args) {
String[] strings = {"jute", "hemp", "nylon"};
UnaryFunction<String> sameString = identityFunction();
for (String s : strings) {
System.out.println(sameString.apply(s));
}
Number[] numbers = {1, 2.0, 3L};
UnaryFunction<Number> sameNumber = identityFunction();
for (Number n : numbers) {
System.out.println(sameNumber.apply(n));
}
}
}
我不明白 apply
方法到底做了什么!
这就像获取一个对象并返回自身。为什么?一些无用的样本?
有人能告诉我用例吗?
一个用例是Collectors.toMap()
。
假设您有一个由唯一键标识的项目列表,并且您想要从该唯一键到对象本身的 Map
。
Collectors.toMap()
需要两个函数:
- 一个从对象中提取密钥
- 另一个从对象中提取值
由于值应该是对象本身,因此您需要一个接受对象和 returns 同一对象的函数 - 这是您的身份函数。
阅读有效java第 5 章第 27 项
它讨论了通用单例模式:
Now suppose that you want to provide an identity function. It would be wasteful to create a new one each time it’s required, as it’s stateless. If generics were reified, you would need one identity function per type, but since they’re erased you need only a generic singleton. Here’s how it looks:
public class GenericSingleton<T> {
private static UnaryFunction<Object> IDENTIFY_FUNCTION = new UnaryFunction<Object>() {
@Override
public Object apply(Object args) {
return args;
}
};
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) IDENTITY_FUNCTION;
}
public static void main(String[] args) {
String[] strings = {"jute", "hemp", "nylon"};
UnaryFunction<String> sameString = identityFunction();
for (String s : strings) {
System.out.println(sameString.apply(s));
}
Number[] numbers = {1, 2.0, 3L};
UnaryFunction<Number> sameNumber = identityFunction();
for (Number n : numbers) {
System.out.println(sameNumber.apply(n));
}
}
}
我不明白 apply
方法到底做了什么!
这就像获取一个对象并返回自身。为什么?一些无用的样本?
有人能告诉我用例吗?
一个用例是Collectors.toMap()
。
假设您有一个由唯一键标识的项目列表,并且您想要从该唯一键到对象本身的 Map
。
Collectors.toMap()
需要两个函数:
- 一个从对象中提取密钥
- 另一个从对象中提取值
由于值应该是对象本身,因此您需要一个接受对象和 returns 同一对象的函数 - 这是您的身份函数。