泛型是 Java 编程中的一项强大特性,它允许我们在定义类、接口和方法时使用类型参数,从而使代码更具灵活性和复用性。在自定义类中使用泛型,可以让你创建能够处理任意类型数据的类,同时保持类型安全。
以下是一个示例,展示如何在自定义类中使用泛型:
一、定义一个泛型类
我们可以定义一个泛型类,例如一个简单的容器类,用于存储和操作任意类型的对象。
public class GenericContainer<T> {
private T value;
public GenericContainer(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
@Override
public String toString() {
return "GenericContainer{" +
"value=" + value +
'}';
}
}
二、使用泛型类
在使用泛型类时,你可以指定具体的类型参数,以确保类中的操作类型安全。
public class Main {
public static void main(String[] args) {
// 使用 Integer 类型
GenericContainer<Integer> integerContainer = new GenericContainer<>(42);
System.out.println(integerContainer);
System.out.println("Value: " + integerContainer.getValue());
// 使用 String 类型
GenericContainer<String> stringContainer = new GenericContainer<>("Hello, World!");
System.out.println(stringContainer);
System.out.println("Value: " + stringContainer.getValue());
}
}
三、泛型类的实际应用
1. 泛型类作为容器
以下是一个更具实际意义的泛型类的示例,它实现了一个简单的泛型集合。
public class GenericCollection<T> {
private List<T> elements = new ArrayList<>();
public void addElement(T element) {
elements.add(element);
}
public List<T> getElements() {
return elements;
}
@Override
public String toString() {
return "GenericCollection{" +
"elements=" + elements +
'}';
}
}
2. 使用泛型类
public class Main {
public static void main(String[] args) {
// 使用 Integer 类型
GenericCollection<Integer> integerCollection = new GenericCollection<>();
integerCollection.addElement(1);
integerCollection.addElement(2);
integerCollection.addElement(3);
System.out.println(integerCollection);
System.out.println("Elements: " + integerCollection.getElements());
// 使用 String 类型
GenericCollection<String> stringCollection = new GenericCollection<>();
stringCollection.addElement("Hello");
stringCollection.addElement("World");
System.out.println(stringCollection);
System.out.println("Elements: " + stringCollection.getElements());
}
}
四、泛型类的高级用法
1. 泛型方法
在泛型类中,你还可以定义泛型方法,以进一步增强类的灵活性。
public class GenericMethods<T> {
public <E> void printArray(E[] array) {
for (E element : array) {
System.out.print(element + " ");
}
System.out.println();
}
}
2. 使用泛型方法
public class Main {
public static void main(String[] args) {
GenericMethods<Integer> genericMethods = new GenericMethods<>();
Integer[] integers = {1, 2, 3};
genericMethods.printArray(integers);
String[] strings = {"Hello", "World"};
genericMethods.printArray(strings);
}
}
五、总结
通过在自定义类中使用泛型,我们可以创建更加灵活和通用的代码,同时保持类型安全。泛型类和方法可以处理任意类型的数据,减少了代码的重复性,并提高了代码的可读性和可维护性。希望以上示例能够帮助你更好地理解和应用泛型技术。