泛型
很多时候,我们关心的不是类型,而是能力。针对接口和能力编程,不仅可以复用代码,还可以降低耦合,提高灵活性。
泛型将接口的概念进一步延伸,泛型的字面意思就是广泛的类型。
代码与它们能够操作的数据类型不再绑定在一起,同一套代码可以用于多种数据类型,不仅可以复用代码,降低耦合,还可以提高代码的可读性和安全性。
在java中,类,接口,方法都可以是泛型的。
泛型类
public class Pair<T> {
T first;
T second;
public Pair(T first, T second) {
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public T getSecond() {
return second;
}
}
public class Pair<U, V> {
U first;
V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
public U getFirst() {
return first;
}
public V getSecond() {
return second;
}
}
java编译器在编译的时候,会擦除类型参数T,替换成Object,插入必要的类型转换。也就是会将泛型代码转换成非泛型代码。
也就是说java泛型是通过擦除实现的。
既然可以通过擦除实现泛型,为啥还会设计泛型这个形式,也就是泛型的好处是什么?
更好的安全性
更好的可读性
编译的时候就会提示传参是否安全,这个就是类型安全。也就是说,通过使用泛型,开发环境和编译器能确保不会使用错类型。
容器类
泛型类最常见的用途是作为容器类(容纳并管理多项数据的类)。所谓容器类,简单地说,就是容纳并管理多项数据的类。
public class DynamicArray<E> {
private static final int DEFAULT_CAPACITY = 10;
private int size;
private Object[] elementData;
public DynamicArray() {
elementData = new Object[DEFAULT_CAPACITY];
}
private void ensureCapacity(int minCapacity) {
int oldCapacity = elementData.length;
if (oldCapacity >= minCapacity) {
return;
}
int newCapacity = oldCapacity * 2;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
public void add(E e){
ensureCapacity(size +1);
elementData[size++] = e;
}
public E get(int index){
return (E) elementData[index];
}
public int size(){
return size;
}
public E set(int index,E element){
E oldValue = get(index);
elementData[index] = element;
return oldValue;
}
public static <T> int indexOf(T[] arr, T elm) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(elm)) {
return i;
}
}
return -1;
}
}
泛型方法
public static <T> int indexOf(T[] arr, T elm) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(elm)) {
return i;
}
}
return -1;
}
类型参数为T,放在返回值前面,
与泛型类一样,类型参数也可以传递多个
public static <U, V> Pair<U, V> makePair(U first, V second) {
Pair<U, V> pair = new Pair<U, V>(first, second);
return pair;
}
泛型接口
public interface Comparable<T>{
public int compareTo(T to);
}
泛型类型的限定