1. 集合中的泛型
package com.practice;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Practice {
public static void main(String[] args) {
//泛型,会自动检查添加元素的类型
List<String> list = new ArrayList<>();
list.add("AA");
list.add("BB");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
//不用类型强转
System.out.println(iterator.next());
}
}
}
2. 泛型类、泛型方法
package com.practice;
import java.util.ArrayList;
import java.util.List;
/**
* 使用泛型类、泛型方法
*
* @author yyx 2019年8月31日
*/
public class Practice {
public static void main(String[] args) {
Goods goods = new Goods("苹果");
Order<Goods> order = new Order<>();
order.setT(goods);
order.add();
System.out.println(order.list.get(0).getGoodsName());
System.out.println(order.getE(goods).getGoodsName());
}
}
// 泛型类
class Order<T> {
private T t;
List<T> list = new ArrayList<>();
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public void add() {
list.add(t);
}
/**
* 泛型方法
*
* @param e
* @return
*/
public <E> E getE(E e) {
return e;
}
}
class Goods {
private String goodsName;
public Goods(String goodsName) {
super();
this.goodsName = goodsName;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
}
3. 泛型接口
package com.practice;
public class Practice {
public static void main(String[] args) {
SubShowInfo subShowInfo = new SubShowInfo();
subShowInfo.setUserName("jtx");
System.out.println(subShowInfo.getInfo());
}
}
/**
* 泛型接口
*/
interface ShowInfo<E> {
E getInfo();
}
class SubShowInfo implements ShowInfo<String> {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String getInfo() {
return this.userName;
}
}