泛型:泛型的意思是参数化类型。使用该特性创建的类、接口以及方法,可以作为参赛指定所操作数据的类型。
JDK1.5版本以后出现新特性。用于解决安全问题,是一个类型安全机制。
好处
1.将运行时期出现问题ClassCastException,转移到了编译时期。,
方便于程序员解决问题。让运行时问题减少,安全。
2,避免了强制转换麻烦。
泛型格式:通过<>来定义要操作的引用数据类型。
在使用java提供的对象时,什么时候写泛型呢?
通常在集合框架中很常见,
只要见到<>就要定义泛型。
其实<> 就是用来接收类型的。
当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。
注意:泛型只能使用引用类型
当声明泛型类的实例时,传递过来的参数必须是引用类型。不能使用基本类型,如int或char等。
<pre name="code" class="java">public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("abc01");
al.add("abc0991");
al.add("abc014");
Iterator<String> it = al.iterator();
while(it.hasNext())
{
String s = it.next();
System.out.println(s+":"+s.length());
}
}
什么时候定义泛型类?当类中要操作的引用数据类型不确定的时候,早期定义Object来完成扩展。现在定义泛型来完成扩展。
泛型类定义的泛型,在整个类中有效。如果被方法使用,那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。为了让不同方法可以操作不同类型,而且类型还不确定。那么可以将泛型定义在方法上。
class Demo<T> //泛型类
{
public void show(T t)
{
System.out.println("show:"+t);
}
public <Q> void print(Q q) //泛型方法
{
System.out.println("print:"+q);
}
public static <W> void method(W t)
{
System.out.println("method:"+t);
}
}
class Test
{
public static void main(String[] args)
{
Demo <String> d = new Demo<String>();
d.show("haha");
d.print(5);
d.print("hehe");
Demo.method("hahahahha");
}
}
interface Inter<T>
{
void show(T t);
}
class InterImpl<T> implements Inter<T>
{
public void show(T t)
{
System.out.println("show :"+t);
}
}
class Test
{
public static void main(String[] args)
{
InterImpl<Integer> i = new InterImpl<Integer>();
i.show(4);
}
}
泛型的限定;
? extends E: 可以接收E类型或者E的子类型。上限。
? super E: 可以接收E类型或者E的父类型。下限
class Test
{
public static void main(String[] args)
{
ArrayList<Student> al1 = new ArrayList<Student>();
al1.add(new Student("abc--1"));
al1.add(new Student("abc--2"));
al1.add(new Student("abc--3"));
printColl(al1);
}
public static void printColl(Collection<? extends Person> al)
{
Iterator<? extends Person> it = al.iterator();
while(it.hasNext())
{
System.out.println(it.next().getName());
}
}
}
class Person
{
private String name;
Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
}