泛型类
前面已经讲过泛型的作用 就如同看门老大爷一样.
下面是基础代码
public class Box<T> {
private T data;
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
在此处<T>如同泛类是对输入类型的限制
其中 private T data中的T如同int 是类型的定义
泛型 方法
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
与泛型类大同小异. 前面学懂自然明白.
泛型接口
interface List<T> {
void add(T element);
T get(int index);
}
与前面一样 T指定返回类型
继承与通配符
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class BoxUtil {
public static double getWeight(Box<? extends Weightable> box) {//如果?super表示所有父类
return box.get().getWeight();
}
}
public interface Weightable {
double getWeight();
}
public class Apple implements Weightable {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
public static void main(String[] args) {
Box<Apple> box = new Box<>();
Apple apple = new Apple(0.5);
box.set(apple);
double weight = BoxUtil.getWeight(box);
System.out.println("Weight: " + weight);
}
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class BoxWithWeight<T extends Weightable> extends Box<T> {
public double getWeight() {
return get().getWeight();
}
}
public interface Weightable {
double getWeight();
}
public class Apple implements Weightable {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
public static void main(String[] args) {
BoxWithWeight<Apple> box = new BoxWithWeight<>();
Apple apple = new Apple(0.5);
box.set(apple);
double weight = box.getWeight();
System.out.println("Weight: " + weight);
}