深入理解 Java 泛型
JAVA乐园
共 15150字,需浏览 31分钟
·
2021-09-19 15:04
泛型的产生
class stack {
push(参数类型) //入栈算法
pop(参数类型) //出栈算法
}
class stack<参数模板 T> {
push(T) //入栈算法
pop(T) //出栈算法
}
class s {
push(int) //入栈算法
pop(int) //出栈算法
}
Java中的泛型
Java的伪泛型,泛型擦除
public static void main(String[] args) {
Class c1 = new ArrayList<String>().getClass();
Class c2 = new ArrayList<Integer>().getClass();
System.out.println(c1 == c2);
}
Java编译器的类型转换和类型检查
类型自动转换
public class Wrapper<T> {
private T field;
public void setField(T field) {
this.field = field;
}
public T getField() {
return field;
}
}
public void test() throws Exception {
Wrapper<Integer> wrapper1 = new Wrapper<>();
Wrapper<String> wrapper2 = new Wrapper<>();
wrapper1.setField(1);
int field1 = wrapper1.getField();
wrapper2.setField("hello generics");
String field2 = wrapper2.getField();
}
public void test() throws Exception {
Wrapper wrapper1 = new Wrapper();
Wrapper wrapper2 = new Wrapper();
wrapper1.setField(Integer.valueOf(1));
int field1 = ((Integer)wrapper1.getField()).intValue();
wrapper2.setField("hello generics");
String field2 = (String)wrapper2.getField();
}
类型检查
private void fun(Wrapper<Integer> wrapper){
}
private void fun(Wrapper<String> wrapper){
}
public class Problem<T> extends Exception{......}
try{
}catch(Problem<Integer> e1){
//...
}catch(Problem<Number> e2){
//...
}
public class Wrapper<T> {
private final int SIZE = 10;
private T field;
public void setField(T field) {
this.field = field;
}
public T getField() {
return field;
}
private void create() {
field = new T(); // Error
if (field instanceof T) {
} // Error
T[] array = new T[SIZE]; // Error
T[] array = (T) new Object[SIZE]; // Unchecked warning
}
}
Wrapper<String> wrapper = new Wrapper();
wrapper.create();
对应:field = new String();
if(filed instanceof String){}
String[] array=new String[SIZE];
String[] array= String new Object[SIZE];
ArrayList<String> arrayList1=new ArrayList();
arrayList1.add("1");//编译通过
arrayList1.add(1);//编译错误
String str1=arrayList1.get(0);//返回类型就是String
ArrayList arrayList2=new ArrayList<String>();
arrayList2.add("1");//编译通过
arrayList2.add(1);//编译通过
Object object=arrayList2.get(0);//返回类型就是Object
Java数组的“泛型化”
Wrapper<String>[] wrapperArr1 = new Wrapper<String>[2]; //error
Wrapper<String>[] wrapperArr2 = new Wrapper[2];//Unchecked warning
It is a compile-time error if the component type of the arra being initialized is not reifiable.
A type is reifiable if and only if one of the following holds:
- It refers to a non-generic class or interface type declaration.
- ... ..
通配符
通配符的产生
class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
public class CovariantArrays {
public void main(String[] args) {
Fruit[] fruit = new Apple[10];
List<Fruit> fruits=new ArrayList<Apple>();//error
fruit[0] = new Apple(); // OK
fruit[1] = new Jonathan(); // OK
// Runtime type is Apple[], not Fruit[] or Orange[]:
try {
// Compiler allows you to add Fruit:
fruit[0] = new Fruit(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
try {
// Compiler allows you to add Oranges:
fruit[0] = new Orange(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
}
}
List<Fruit> fruits=new ArrayList<Apple>();//error
上边界限定通配符
List<?extends Fruit> fruits = new ArrayList<Apple>();
ArrayList<? extends Fruit> fruits = new ArrayList<Apple>();
fruits.add(new Fruit());// Error
Fruit apple = fruits.get(0);
下边界限定通配符
void writeTo(List<? super Apple> apples) {
apples.add(new Apple());
apples.add(new Jonathan());
// apples.add(new Fruit()); // Error
// Apple apple=apples.get(0);// Error
}
无边界通配符
Kotlin的泛型
ArrayList<? extends Fruit> fruits = new ArrayList<Apple>();
Fruit apple = fruits.get(0);
fruits.add(new Fruit());// Error
void writeTo(List<? super Apple> apples) {
apples.add(new Apple());
apples.add(new Jonathan());
// apples.add(new Fruit()); // Error
// Apple apple=apples.get(0);// Error
}
val fruits:ArrayList<out Fruit> = ArrayList()
val apple:Fruit = fruits.get(0)
fruits.add(Fruit()) // Error
void writeTo(apples : ArrayList<in Apple>) {
apples.add(Apple());
apples.add(Jonathan());
// apples.add(Fruit()); // Error
// val apple:Apple = apples.get(0);// Error
}
fun <T : Comparable<T>> sort(list: List<T>) {
// ……
}
sort(listOf(1, 2, 3)) // OK。Int 是 Comparable<Int> 的子类型
sort(listOf(HashMap<Int, String>())) // 错误:HashMap<Int, String> 不是 Comparable<HashMap<Int, String>> 的子类型
fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T>
where T : Comparable<T>,
T : Cloneable {
return list.filter { it > threshold }.map { it.clone() }
source: //ethanhua.github.io/2018/01/09/genericity/
喜欢,在看
评论