mirror of
https://github.com/Jueee/effective-Java.git
synced 2025-03-14 03:10:42 +08:00
优先考虑类型安全的异构容器
This commit is contained in:
parent
65d6670592
commit
1f4172cbe7
8
ch05泛型/33.优先考虑类型安全的异构容器.md
Normal file
8
ch05泛型/33.优先考虑类型安全的异构容器.md
Normal file
@ -0,0 +1,8 @@
|
||||
## 优先考虑类型安全的异构容器
|
||||
|
||||
泛型的常见用法包括集合,如 `Set<E`> 和 `Map<K,V>` 和单个元素容器,如 `ThreadLocal<T>` 和 `AtomicReference<T>`。 在所有这些用途中,它都是参数化的容器。 这限制了每个容器只能有固定数量的类型参数。
|
||||
|
||||
**示例代码**:[Item33Example01.java](Generics/src/main/java/com/jueee/item33/Item33Example01.java):参数化键(key)而不是容器。 然后将参数化的键提交给容器以插入或检索值。 泛型类型系统用于保证值的类型与其键一致。
|
||||
|
||||
`Favorites` 实例是类型安全的:当你请求一个字符串时它永远不会返回一个整数。 它也是异构的:与普通 Map 不同,所有的键都是不同的类型。我们将 `Favorites` 称为类型安全异构容器(`typesafe heterogeneous container`)。
|
||||
|
@ -0,0 +1,34 @@
|
||||
package com.jueee.item33;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Item33Example01 {
|
||||
|
||||
// Typesafe heterogeneous container pattern - client
|
||||
public static void main(String[] args) {
|
||||
Favorites f = new Favorites();
|
||||
f.putFavorite(String.class, "Java");
|
||||
f.putFavorite(Integer.class, 0xcafebabe);
|
||||
f.putFavorite(Class.class, Favorites.class);
|
||||
|
||||
String favoriteString = f.getFavorite(String.class);
|
||||
int favoriteInteger = f.getFavorite(Integer.class);
|
||||
Class<?> favoriteClass = f.getFavorite(Class.class);
|
||||
System.out.printf("%s %x %s%n", favoriteString, favoriteInteger, favoriteClass.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Favorites {
|
||||
private Map<Class<?>, Object> favorites = new HashMap<>();
|
||||
|
||||
public <T> void putFavorite(Class<T> type, T instance) {
|
||||
favorites.put(Objects.requireNonNull(type), instance);
|
||||
}
|
||||
|
||||
public <T> T getFavorite(Class<T> type) {
|
||||
return type.cast(favorites.get(type));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user