题目
实现一个泛型方法用于交换数组中两个元素的位置
信息
- 类型:问答
- 难度:⭐
考点
泛型方法定义,类型参数使用,数组操作
快速回答
实现步骤:
- 定义泛型方法:在返回类型前添加类型参数声明
<T> - 参数声明:使用
T[] array接收泛型数组 - 交换逻辑:通过临时变量交换索引
i和j的元素 - 边界检查:添加索引有效性验证
原理说明
泛型方法允许在方法签名中声明类型参数(如 <T>),使方法能处理多种数据类型而不需强制类型转换。本例中通过泛型方法实现类型安全的数组元素交换,编译器会确保传入的数组和操作类型一致。
代码示例
public class ArrayUtils {
// 泛型方法定义
public static <T> void swap(T[] array, int i, int j) {
if (i < 0 || i >= array.length || j < 0 || j >= array.length) {
throw new IllegalArgumentException("索引越界");
}
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) {
// 字符串数组示例
String[] words = {"Hello", "World"};
swap(words, 0, 1); // 交换后:["World", "Hello"]
// 整数数组示例(自动装箱)
Integer[] numbers = {1, 2, 3};
swap(numbers, 0, 2); // 交换后:[3, 2, 1]
}
}最佳实践
- 类型安全:使用泛型避免运行时
ClassCastException - 边界检查:始终验证数组索引防止
ArrayIndexOutOfBoundsException - 静态方法:工具方法建议声明为
static方便调用
常见错误
- 遗漏类型参数声明:错误写法
public static void swap(T[]...)会导致编译错误 - 基本类型数组:尝试传入
int[]会报错,需改用包装类如Integer[] - 空指针风险:未检查
array == null可能引发NullPointerException
扩展知识
- 类型擦除:编译后泛型类型会被替换为
Object(或边界类型),运行时无泛型信息 - 泛型限制:不能创建泛型数组如
new T[size],但可操作传入的泛型数组 - 通配符应用:若需处理未知子类型数组,可用
? extends T,但本例不需要