泛型是类型的参数表示,简单的几种应用形式:(作用,更小的类型转换抛出,只要编译时没出现警告,就不会出现运行时ClassCastException无需记向下转换的具体类型)
1.class Text<T>//以String类型实例化泛型T为例
2.class Text<T extends List>//只有List的实现类才能作为参数传入
3.class Text<T> //限定类型持有者的范围
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapTest
{
public static void main(String[] args)
{
TreeMap<Person,String> map = new TreeMap<Person,String>(new Person2<Person>());
map.put(new Person("zhangsan",15,"beijing"), "第一名");
map.put(new Person("lisi",20,"tianjin"),"第二名");
map.put(new Person("wangwu ",25,"shagnhai"), "第三名");
Set<Map.Entry<Person,String>> set = map.entrySet();
for(Iterator<Map.Entry<Person,String>> itr = set.iterator(); itr.hasNext();)
{
Map.Entry<Person,String> mentry = itr.next();
int age = (mentry.getKey()).getAge();
System.out.println(age);
System.out.println(mentry.getValue());
}
}
}
class Person2<T> implements Comparator<T>
{
public int compare(T o1,T o2)
{
Person p1 = (Person)o1;
Person p2 = (Person)o2;
return p1.age - p2.age;
}
}
class Person
{
String name;
int age;
String address;
public Person(String name, int age, String address)
{
this.name = name;
this.address= address;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}