java 成员函数使用泛型
时间: 2024-02-07 20:41:18 浏览: 26
可以将泛型参数放在函数名前面的尖括号中,用于限制函数参数和返回值的类型。例如:
```
public <T> T getObject(T[] array, int index) {
return array[index];
}
```
这个函数可以接受任何类型的数组作为参数,并返回该数组中指定索引的元素。使用时可以传入不同类型的参数,例如:
```
String[] strings = {"Hello", "world"};
int[] ints = {1, 2, 3};
String s = getObject(strings, 1); // 返回 "world"
int i = getObject(ints, 0); // 返回 1
```