package com.direct.demo; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Fanxing { public static void main(String[] args) { Gen<String> gen = new Gen<String>("xiaonbai"); System.out.println(gen.getT()); gen.show(); Gen<? extends List> gen2 = null;//通配符的使用 必须是List或者List的子类 gen2 = new Gen<ArrayList>();//无参的构造方法 gen2 = new Gen<LinkedList>(); List list = new ArrayList(); gen2 = new Gen<List>(list);//有参的构造方法,参数是实例化对象 System.out.println("----------------------------------------"); List<Integer> list2 = new ArrayList<Integer>(); list2.add(123); list2.add(456); List<Long> list3 = new ArrayList<Long>(); list3.add(345L); list3.add(42L); gen.print(list2); gen.print(list3); gen.print2(list2); System.out.println("----------------------------------------"); Goods goods = new Goods("加多宝", 100); MyClass<Goods> mClass = new MyClass<Goods>(); mClass.display(goods); //分页 Map<String, Object> map = new HashMap<String, Object>(); map.put("pageNo", 5);//页数5 map.put("pageSize", 20);//每天20条 map.put("pageCount", 1000);//共1000 map.put("goods", goods);//存放的是Goods类型 MyClass<Map<String, Object>> mymap = new MyClass<Map<String,Object>>(); } } //泛型类 class Gen<T>{ private T t1;//泛型成员变量 //泛型构造函数 public Gen(T t1){ this.t1 = t1; } public Gen() { // TODO Auto-generated constructor stub } public T getT(){ return t1; } public <T> void show(){ System.out.println("----->"+t1); } public void print(List<? extends Number> list){ System.out.println(list.get(0));//只能取值,不能设置(add()) //list.add("haohao"); } public void print2(List<? super Integer> li){ System.out.println("super"); System.out.println(li.get(0));//向上 可以取值,也可设值 li.add(230); for (int i = 0; i < li.size(); i++) { System.out.println(li.get(i)); } } } //泛型接口 interface Iennter<Q>{ //接口没有构造方法 public void display(Q q); } //接口的一个实现类 class MyClass<Q> implements Iennter<Q>{ @Override//Q是类型 public void display(Q q) { System.out.println(q);//q为对象引用 } } class Goods{ private String name; private int num; public Goods(String name,int num){ this.name = name; this.num = num; } @Override public String toString() { return "Goods [name=" + name + ", num=" + num + "]"; } }