泛型:
jdk1.5出現(xiàn)的安全機制。
好處:
1,將運行時期的問題ClassCastException轉(zhuǎn)到了編譯時期。
2,避免了強制轉(zhuǎn)換的麻煩。
<>:什么時候用?當操作的引用數(shù)據(jù)類型不確定的時候。就使用<>。將要操作的引用數(shù)據(jù)類型傳入即可.
其實<>就是一個用于接收具體引用數(shù)據(jù)類型的參數(shù)范圍。
在程序中,只要用到了帶有<>的類或者接口,就要明確傳入的具體引用數(shù)據(jù)類型 。
泛型技術是給編譯器使用的技術,用于編譯時期。確保了類型的安全。
運行時,會將泛型去掉,生成的class文件中是不帶泛型的,這個稱為泛型的擦除。
為什么擦除呢?因為為了兼容運行的類加載器。
泛型的補償:在運行時,通過獲取元素的類型進行轉(zhuǎn)換動作。不用使用者在強制轉(zhuǎn)換了。
- 將泛型定義在類上
public class Tool<QQ>{
private QQ q;
public QQ getObject() {
return q;
}
public void setObject(QQ object) {
this.q = object;
}
}
- 將泛型定義在方法上
/**
* 將泛型定義在方法上。
* @param str
*/
public <W> void show(W str){
System.out.println("show : "+str.toString());
}
public void print(QQ str){
System.out.println("print : "+str);
}
注意:
1.泛型必須寫在返回類型修飾符前。
2.當方法靜態(tài)時,不能訪問類上定義的泛型。如果靜態(tài)方法使用泛型,只能將泛型定義在方法上。
/**
* 當方法靜態(tài)時,不能訪問類上定義的泛型。如果靜態(tài)方法使用泛型,
* 只能將泛型定義在方法上。
* @param obj
*/
public static <Y> void method(Y obj){
System.out.println("method:"+obj);
}
- 泛型接口,將泛型定義在接口上,以下兩種實現(xiàn)接口的方式都行,只要看什么時候明確了類型
interface Inter<T>{
public void show(T t);
}
class InterImpl2<Q> implements Inter<Q>{
public void show(Q q){
System.out.println("show :"+q);
}
}
class InterImpl implements Inter<String>{
public void show(String str){
System.out.println("show :"+str);
}
}
泛型的通配符:? 未知類型。
示例代碼:
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("abc");
al.add("hehe");
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(5);
al2.add(67);
printCollection(al);
printCollection(al2);
}
/**
* 迭代并打印集合中元素。
* @param al
*/
public static void printCollection(Collection<?> al) {
Iterator<?> it = al.iterator();
while(it.hasNext()){
// T str = it.next();
// System.out.println(str);
System.out.println(it.next().toString());
}
}
泛型的限定:
? extends E: 接收E類型或者E的子類型對象。上限
一般存儲對象的時候用。因為這樣取出都是按照上限類型來運算的。不會出現(xiàn)類型安全隱患。 比如 添加元素 addAll.
class MyCollection<E>{
public void add(E e){
}
public void addAll(MyCollection<? extends E> e){
}
}
public static void printCollection(Collection<? extends Person> al) {//Collection<Dog> al = new ArrayList<Dog>()
Iterator<? extends Person> it = al.iterator();
while(it.hasNext()){
// T str = it.next();
// System.out.println(str);
// System.out.println(it.next().toString());
Person p = it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}*/
? super E: 接收E類型或者E的父類型對象。 下限。
一般取出對象的時候用。比如比較器。
class TreeSet<Worker>
{
Tree(Comparator<? super Worker> comp);
}
public static void printCollection(Collection<? super Student> al){
Iterator<? super Student> it = al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}