泛型
测试用例1
import org.junit.Test;
public class T {
@Test
public void m() {
Product<String,Integer> product = new Product<>();
product.param(2024);
product.name = "巧克力";
System.out.println("获取属性:"+product.getName());
}
}
class Product<T,E> {
T name;
public void param(E e) {
System.out.println("获取传参:"+e);
}
public T getName() {
return name;
}
}
测试用例2 静态泛型方法
package fanxing;
import org.junit.Test;
public class T {
@Test
public void m() {
Product<String> product = Product.hello("静态泛型方法");
System.out.println(product);
System.out.println(product.data);
}
}
class Product<T> {
public T data;
public static <T> Product<T> hello(T param){
Product<T> product = new Product<>();
product.data = param;
return product;
}
@Override
public String toString() {
return "Product{" +
"data=" + data +
'}';
}
}
测试用例3 上界限定符 vs 下界限定符
import org.junit.Test;
import java.util.*;
public class T {
@Test
public void m3() {
List<? super Cat> cats1 = new ArrayList<Object>();
List<? super Cat> cats2 = new ArrayList<Animal>();
List<? super Cat> cats3 = new ArrayList<Cat>();
}
@Test
public void m2() {
List<? extends Animal> animals1 = new ArrayList<Animal>();
List<? extends Animal> animals2 = new ArrayList<Cat>();
List<? extends Animal> animals3 = new ArrayList<Dog>();
List<? extends Animal> animals4 = new ArrayList<Tiger>();
}
@Test
public void m1_2() {
List<?> annimals1 = new ArrayList<Animal>();
List<?> annimals2 = new ArrayList<Dog>();
List<?> annimals3 = new ArrayList<Cat>();
}
@Test
public void m1_1() {
}
class Animal {
}
class Cat extends Animal {
}
class Tiger extends Cat {
}
class Dog extends Animal {
}
}