Java自定义泛型类案例
基本泛型类示例
// 定义一个简单的泛型类
public class Box<T> {
private T content;
public Box() {}
public Box(T content) {
this.content = content;
}
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public void printType() {
System.out.println("Content type: " + content.getClass().getName());
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
// 存储字符串
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello Generics");
System.out.println(stringBox.getContent()); // Hello Generics
// 存储整数
Box<Integer> integerBox = new Box<>(100);
System.out.println(integerBox.getContent()); // 100
// 存储自定义对象
Box<Person> personBox = new Box<>();
personBox.setContent(new Person("John", 25));
System.out.println(personBox.getContent().getName()); // John
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
}
多个类型参数的泛型类
// 使用多个类型参数
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
@Override
public String toString() {
return "Pair{" + key + "=" + value + "}";
}
}
// 使用示例
public class PairDemo {
public static void main(String[] args) {
// 字符串到整数的映射
Pair<String, Integer> agePair = new Pair<>("John", 25);
System.out.println(agePair); // Pair{John=25}
// 字符串到字符串的映射
Pair<String, String> namePair = new Pair<>("firstName", "John");
System.out.println(namePair); // Pair{firstName=John}
// 混合类型
Pair<Integer, Boolean> statusPair = new Pair<>(1, true);
System.out.println(statusPair); // Pair{1=true}
}
}
带边界限制的泛型类
// 限制类型必须是Comparable的子类
public class BoundBox<T extends Comparable<T>> {
private T[] elements;
private int size;
@SuppressWarnings("unchecked")
public BoundBox(int capacity) {
elements = (T[]) new Comparable[capacity];
size = 0;
}
public void add(T element) {
if (size < elements.length) {
elements[size++] = element;
}
}
public T getMax() {
if (size == 0) return null;
T max = elements[0];
for (int i = 1; i < size; i++) {
if (elements[i].compareTo(max) > 0) {
max = elements[i];
}
}
return max;
}
public T getMin() {
if (size == 0) return null;
T min = elements[0];
for (int i = 1; i < size; i++) {
if (elements[i].compareTo(min) < 0) {
min = elements[i];
}
}
return min;
}
}
// 使用示例
public class BoundBoxDemo {
public static void main(String[] args) {
BoundBox<Integer> numberBox = new BoundBox<>(5);
numberBox.add(45);
numberBox.add(12);
numberBox.add(87);
numberBox.add(33);
System.out.println("Max: " + numberBox.getMax()); // 87
System.out.println("Min: " + numberBox.getMin()); // 12
// 字符串类型,String也实现了Comparable
BoundBox<String> stringBox = new BoundBox<>(3);
stringBox.add("Apple");
stringBox.add("Banana");
stringBox.add("Cherry");
System.out.println("Max: " + stringBox.getMax()); // Cherry
System.out.println("Min: " + stringBox.getMin()); // Apple
}
}
泛型类实现接口
// 定义一个泛型接口
interface Repository<T> {
void save(T item);
T findById(int id);
void delete(T item);
}
// 实现泛型接口的泛型类
public class GenericRepository<T> implements Repository<T> {
private Map<Integer, T> data = new HashMap<>();
private int nextId = 0;
@Override
public void save(T item) {
data.put(nextId++, item);
System.out.println("Saved: " + item);
}
@Override
public T findById(int id) {
return data.get(id);
}
@Override
public void delete(T item) {
data.values().remove(item);
System.out.println("Deleted: " + item);
}
}
// 使用示例
public class RepositoryDemo {
public static void main(String[] args) {
// 用户仓库
Repository<User> userRepo = new GenericRepository<>();
userRepo.save(new User(1, "Alice"));
userRepo.save(new User(2, "Bob"));
User found = userRepo.findById(1);
System.out.println("Found: " + found.getName()); // Alice
// 产品仓库
Repository<Product> productRepo = new GenericRepository<>();
productRepo.save(new Product("Laptop", 999.99));
productRepo.save(new Product("Phone", 599.99));
}
}
class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() { return name; }
}
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
}
实际案例:通用缓存类
// 带过期时间的缓存
public class Cache<K, V> {
private Map<K, CacheItem<V>> cache;
private long defaultExpirationMillis;
private static class CacheItem<V> {
private V value;
private long timestamp;
CacheItem(V value, long timestamp) {
this.value = value;
this.timestamp = timestamp;
}
boolean isExpired(long expirationMillis) {
return System.currentTimeMillis() - timestamp > expirationMillis;
}
}
public Cache(long defaultExpirationMillis) {
this.cache = new ConcurrentHashMap<>();
this.defaultExpirationMillis = defaultExpirationMillis;
}
public void put(K key, V value) {
cache.put(key, new CacheItem<>(value, System.currentTimeMillis()));
}
public void put(K key, V value, long expirationMillis) {
cache.put(key, new CacheItem<>(value, System.currentTimeMillis()));
}
public V get(K key) {
CacheItem<V> item = cache.get(key);
if (item == null) return null;
if (item.isExpired(defaultExpirationMillis)) {
cache.remove(key);
return null;
}
return item.value;
}
public boolean containsKey(K key) {
return get(key) != null;
}
public void remove(K key) {
cache.remove(key);
}
public void clear() {
cache.clear();
}
public int size() {
return cache.size();
}
}
// 使用示例
public class CacheDemo {
public static void main(String[] args) throws InterruptedException {
// 创建缓存,默认过期时间5秒
Cache<String, String> cache = new Cache<>(5000);
// 存入数据
cache.put("user:1", "Alice");
cache.put("user:2", "Bob");
// 立即获取
System.out.println(cache.get("user:1")); // Alice
// 等待6秒后获取(数据过期)
Thread.sleep(6000);
System.out.println(cache.get("user:1")); // null(过期了)
// 重新存入
cache.put("user:1", "Alice Updated");
System.out.println(cache.get("user:1")); // Alice Updated
}
}
关键要点
-
类型参数命名约定:

- T - Type(类型)
- E - Element(元素)
- K - Key(键)
- V - Value(值)
- N - Number(数字)
-
类型边界:
T extends Comparable<T>- 限制类型必须实现ComparableT extends Number- 限制类型必须是Number或其子类
-
注意事项:
- 不能创建泛型类型的数组
- 不能使用instanceof检查泛型类型
- 静态成员不能使用类型参数
- 泛型类可以有多个类型参数
通过以上案例,你可以看到泛型类如何提供类型安全、代码复用和灵活性。