You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.9 KiB
51 lines
1.9 KiB
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class GenericDemo {
|
|
public static void main(String[] args) {
|
|
// 测试 Box 泛型类
|
|
System.out.println("===== 测试 Box 泛型类 =====");
|
|
Box<String> stringBox = new Box<>("Hello, Generics!");
|
|
System.out.println(stringBox);
|
|
|
|
Box<Integer> integerBox = new Box<>(100);
|
|
System.out.println(integerBox);
|
|
|
|
integerBox.setContent(200);
|
|
System.out.println("修改后:" + integerBox);
|
|
|
|
Box<Double> doubleBox = new Box<>();
|
|
System.out.println("空盒子:" + doubleBox);
|
|
System.out.println("是否为空:" + doubleBox.isEmpty());
|
|
|
|
// 测试 Pair 泛型类
|
|
System.out.println("\n===== 测试 Pair 泛型类 =====");
|
|
Pair<String, Integer> nameAgePair = new Pair<>("张三", 25);
|
|
System.out.println(nameAgePair);
|
|
System.out.println("姓名:" + nameAgePair.getKey());
|
|
System.out.println("年龄:" + nameAgePair.getValue());
|
|
|
|
Pair<String, String> countryCapitalPair = new Pair<>("中国", "北京");
|
|
System.out.println(countryCapitalPair);
|
|
|
|
// 测试泛型方法
|
|
System.out.println("\n===== 测试泛型方法 =====");
|
|
String[] strArray = {"Java", "Python", "C++", "JavaScript"};
|
|
System.out.print("字符串数组:");
|
|
GenericUtils.printArray(strArray);
|
|
|
|
Integer[] intArray = {1, 2, 3, 4, 5};
|
|
System.out.print("原始数组:");
|
|
GenericUtils.printArray(intArray);
|
|
|
|
GenericUtils.swap(intArray, 0, 4);
|
|
System.out.print("交换后数组:");
|
|
GenericUtils.printArray(intArray);
|
|
|
|
List<Double> doubleList = new ArrayList<>();
|
|
doubleList.add(1.5);
|
|
doubleList.add(2.5);
|
|
doubleList.add(3.5);
|
|
System.out.println("列表元素数量:" + GenericUtils.countListElements(doubleList));
|
|
}
|
|
}
|