public class Container
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
public class Wrapper
private T content;
public Wrapper(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
}
public class GenericStack
private List<T> elements = new ArrayList<>();
public void push(T element) {
elements.add(element);
}
public T pop() {
if (elements.isEmpty()) {
return null;
}
return elements.remove(elements.size() - 1);
}
public boolean isEmpty() {
return elements.isEmpty();
}
}
public class SimpleCache<K, V> {
private Map<K, V> cache = new HashMap<>();
public void put(K key, V value) {
cache.put(key, value);
}
public V get(K key) {
return cache.get(key);
}
}
public void printList(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
// 泛型之前 List list = new ArrayList(); list.add("hello"); String str = (String) list.get(0); // 需要显式转型
// 使用泛型后
List
你可能想看: