泛型概述
JDK1.5版本出现的新特性,为了解决安全问题,是个安全机制。
好处:1.将运行时期的classCastException,转移到了编译时期,方便程序员解决问题,让运行时
更安全。
2.避免了强制转换的麻烦。
代码:
import java.util.*;
class GenericDemo
{
public static void main(String[] args){
ArrayList<String> al = new ArrayList();
al.add("adfda");
al.add("fas");
al.add("asdf");
Iterator<String>it = al.iterator();
while(it.hasNext())
{
String s = it.next();
System.out.println(s+"****"+s.length());
}
}
}
格式:通过<>来定义要操作的引用数据类型。那么什么时候定义泛型呢?
通常在集合框架中常见,只要见到<>就要定义泛型,其实<>就是来接收类型的,
当使用集合时,将集合的中要存储的数据类型作为参数传递到<>即可。
实例演示:
import java.util.*;
class GenericDemo2
{
public static void main(String[] args){
TreeSet<String> ts = new TreeSet(new LenComparator);
ts.add("asd");
ts.add("wer");
ts.add("hggf");
Iterator it = ts.iterator();
while(it.hasNext()){
String str = it.next();
System.out.println(str+"####"+str.length());
}
}
}
class LenComparator implements Comparator<String>
{
public int LenComparator(String o1,String o2){
int num = new Integer(o1.length()).compareTo(new Integer (o2.length()));
if(num == 0)
return o1.compareTo(o2);
return num;
}
}
泛型类:当类中要操作的引用数据类型不确定的时候,早起定义Object来完成扩展,现在
定义泛型来进行扩展。
class Utils<QQ>
{
private QQ qq;
public void setObject(QQ qq){
this.q = q;
}
public QQ getObject(){
return q;
}
}
class Generic3
{
public static void main(String[] args){
Utils<Worker> u = new Utils<Worker>();
u.setObject(new Student());
Worker w = u.getObject();
}
}
泛型方法:泛型类定义的泛型,在整个类中有效,如果被对象使用,
那么泛型类的对象明确要操作的具体类型以后,所有方法操作的类型
就已经固定了,为了让不同方法操作不同类型,而且类型还不确定,
那么可以将泛型定义在方法上。
//class Demo<T>//泛型定义在类上
//{
// public void show(T t){
// System.out.println("show: "t);
// }
// public void print(T t){
// System.out.println("print: "t);
// }
//}
class Demo1
{
public <T>void show(T t){
}
public <Q>void print(Q q){
}
}
class GenericDemo4
{
public static void main(String[] args){
Demo<String>d = new Demo<String>();
d.show("你好");
d.print("hello");
}
}
此外还可以同时定义类和方法为泛型
特殊之处:静态方法不可以访问类上定义的泛型,如果静态方法要操作的
数据类型不确定,可以将泛型定义在方法上。
泛型定义在方法上时,泛型类的位置在返回值类型前面,修饰符后面,
(如定义在void前static 后)
class Demo3<T>
{
public void show(T t){
//与类泛型一致
}
public <Q>void print(Q q){
//自己的泛型类型
}
public static <W>void method(W w){
}
}
泛型高级应用
?:通配符。也可以叫占位符。
泛型限定:
? extends E:可以接收E类型或者E的子类型,上限。
? super E:可以接收E类型或者E的父类型,下限。
import java.util.*;
class GenericDemo5
{
public static void main(String[] args){
ArrayList<String> al1 = new ArrayList<String>();
al1.add("abc");
al1.add("def");
al1.add("ghe");
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(4);
al2.add(5);
al2.add(6);
//调用
printColl(al1);
printColl(al2);
}
// public static void printColl(ArrayList<?>al){
// Iterator<?>it = al.iterator();
// while(it.hasNext()){
// System.out.println(it.next());
// }
// }//注意?和T的区别,?不可以操作数据,T可以对数据进行接收操作。
public static <T>void printColl(ArrayList<T>al){
Iterator<T>it = al.iterator();
while(it.hasNext()){
T t = it.next();
System.out.println(t);
}
}
}