1 泛型
- 传入的必须是类或接口,不能是基本数据类型如int.
- 没有传入就默认使用Object
- 静态成员不能使用泛型
1.1 泛型类的简单例子
public static void main(String[] args) {
Person<String> person = new Person<String>("Curry");
person.show();
Person<Integer> person2 = new Person<Integer>(100);
person2.show();
}
class Person<E> {
E s ;
public Person(E s) {
this.s = s;
}
public E f() {
return s;
}
public void show() {
System.out.println(s.getClass());
}
}
1.2 泛型接口的简单例子
- 泛型接口的类型, 在继承接口或者实现接口时确定
- 没有指定类型,默认为Object
interface IUsb<U, R> {
int n = 10;
R get(U u);
void hi(R r);
void run(R r1, R r2, U u1, U u2);
default R method(U u) {
return null;
}
}
1.3 泛型方法的简单例子
public class CustomMethodGeneric {
public static void main(String[] args) {
Car car = new Car();
car.fly("宝马", 100);
System.out.println("=======");
car.fly(300, 100.1);
Fish<String, ArrayList> fish = new Fish<>();
fish.hello(new ArrayList(), 11.3f);
}
}
class Car {
public void run() {
}
public <T, R> void fly(T t, R r) {
System.out.println(t.getClass());
System.out.println(r.getClass());
}
}
class Fish<T, R> {
public void run() {
}
public<U,M> void eat(U u, M m) {
}
public void hi(T t) {
}
public<K> void hello(R r, K k) {
System.out.println(r.getClass());
System.out.println(k.getClass());
}
}
1.4 形参上的泛型
- <?> :可以传入任何类
- <? extends A> :可以传入A及A的子类
- <? super A> :可以传入A及A的父类
public static void printCollection2(List<? extends AA> c) {
for (Object object : c) {
System.out.println(object);
}
}
public static void printCollection1(List<?> c) {
for (Object object : c) {
System.out.println(object);
}
}
public static void printCollection3(List<? super AA> c) {
for (Object object : c) {
System.out.println(object);
}
}