JDK 1.5后出现泛型。
如果用泛型,则TreeSetDemo中创建容器时就可制定存储类型,强转可以不使用,代码变为:
import java.util.*;
class Cmprt implements Comparator<String> //比较器
{
public int compare(String s1, String s2) //不需要强转类型了
{
int result = new Integer(s1.length()).compareTo(new Integer(s2.length())); //调用Integer的compareTo方法比较
if(result != 0)
return result;
else
return s1.compareTo(s2); //如果长度相等,比较字符串
}
}
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet<String> t = new TreeSet<String>(new Cmprt()); //Cmprt其实可以写为匿名内部类
t.add("aaaaaaaa");
t.add("dsads");
t.add("iojojoi");
t.add("sbcc");
t.add("abcd");
Iterator<String> i = t.iterator(); //迭代器也使用泛型
while(i.hasNext())
System.out.println(i.next());
}
}
自己创建一个简单的泛型类:
//泛型类
class GenericClass<T>
{
public void show(T t)
{
System.out.println(t);
}
}
//测试类
class GenericClassDemo
{
public static void main(String[] args)
{
GenericClass<String> g = new GenericClass<String>();
g.show("aaaaaaaaaa");
}
}
以上例子类型一确定,show方法只能打印确定类型;如果想要调用方法打印任意类型,可以只在方法中定义泛型:
//带有泛型方法的类
class GenericMethod
{
public <T> void show(T t) //泛型方法。<>放在放在返回值类型的前面
{
System.out.println(t);
}
}
//测试类
class GenericMethodDemo
{
public static void main(String[] args)
{
GenericMethod g = new GenericMethod();
g.show("aaaaaaaaaa");
}
}
静态方法不可以访问类上定义的泛型,原因很简单。静态方法若要用泛型,只能定义在方法上。
再来看一下泛型定义在接口上:
//接口:
interface In<T>
{
void show(T t);
}
//子类实现接口,保留泛型
class ImpleIn<T> implements In<T>
{
public void show(T t)
{
System.out.println(t);
}
}
//测试类
class Demo
{
public static void main(String[] args)
{
ImpleIn<String> i = new ImpleIn<String>();
i.show("dasdasd");
}
}
泛型定义在接口上(2)
//接口:
interface In<T>
{
void show(T t);
}
//子类,明确泛型类型
class ImpleIn implements In<String>
{
public void show(String s)
{
System.out.println(s);
}
}
//测试类
class Demo
{
public static void main(String[] args)
{
ImpleIn i = new ImpleIn();
i.show("dasdasd");
}
}
泛型的高级应用:泛型限定。
?:通配符,也可以理解为占位符。
? extends E:上限限定。
? super E:下限限定。
import java.util.*;
//父类Person
class Person
{
private String name;
public Person(String s)
{
this.name = s;
}
public String toString()
{
return this.name;
}
}
//子类Student:
class Student extends Person
{
public Student(String s)
{
super(s);
}
}
class Demo1
{
public static void main(String[] args)
{
ArrayList<Student> al1 = new ArrayList<Student>();
al1.add(new Student("zhangsan"));
al1.add(new Student("lisi"));
al1.add(new Student("wangwu"));
al1.add(new Student("zhaoliu"));
ArrayList<Person> al2 = new ArrayList<Person>();
al2.add(new Person("aaa"));
al2.add(new Person("bbb"));
al2.add(new Person("ccc"));
print(al1);
print(al2);
}
public static void print(ArrayList<? extends Person> al) //泛型限定
{
Iterator<? extends Person> it = al.iterator(); //泛型限定
while(it.hasNext())
{
System.out.println(it.next());
}
}
}