泛型
泛型
1 为什么要有泛型
2 在集合中使用泛型
ArrayList<Integer> list = new ArrayList<>();//jdk7新特性, 类型推断
list.add(78);
list.add(88);
list.add(77);
list.add(66);
//遍历方式一:
for(Integer i : list){
//不需要强转
System.out.println(i);
}
//遍历方式二:
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Tom1",34);
map.put("Tom2",44);
map.put("Tom3",33);
map.put("Tom4",32);
//添加失败
//map.put(33, "Tom");
Set<Entry<String,Integer>> entrySet = map.entrySet();
Iterator<Entry<String,Integer>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Entry<String,Integer> entry = iterator.next();
System.out.println(entry.getKey() + "--->" + entry.getValue());
}
-
集合接口或集合类在jdk5.0时都修改为带泛型的结构
-
在实例化集合类的时候,可以指明泛型类型
-
指明完以后,在集合类或接口中凡是定义类或接口时,内部结构使用类的泛型的位置,都指定为实例化的泛型类型
-
注意点:泛型的类型必须是类,不能是基本数据类型。需要用到基本数据类型的位置,使用包装类封装
-
如果实例化时,没有指明泛型的类型。默认类型为java.lang.Object类型
-
自然排序
定制排序
3 自定义泛型
3.1 泛型类、泛型接口
如果定义了泛型类,实例化没有指明类的泛型,则认为此泛型类型为Object类型
要求:如果大家定义了类是带泛型的,建议在实例化时要指明类的泛型
public class Order<T>{
String orderName;
int orderId;
T orderT;
public Order(){
//编译不通过
//T[] arr = new T[10];
T[] arr = (T[])new Object[10];
}
public Order(String orderName, int orderId, T orderT){
this.orderName = orderName;
this.orderId = orderId;
this.orderT = orderT;
}
public T getOrderT{
return orderT;
}
public void setOrderT(T orderT){
this