?? test01.java
字號:
package new5generic;
import java.util.*;
/*
* 泛型的基本用法
*/
public class test01 {
public static void main(String[] args) {
HashSet<String> hs=new HashSet<String>();//加入一個泛型參數
hs.add("hello");//類型不安全
hs.add("hehe");
//hs.add(5);//加別的對象時編譯器會報錯
Iterator<String> it=hs.iterator();
while(it.hasNext()){
String str=it.next();//可以直接得到一個string對象,不用像以前一樣強轉
}
for(String str:hs){
System.out.println(str);
}
}
}
public class test02 {
public static void main(String[] args) {
List<Integer> list1=new ArrayList<Integer>();//泛型基類型可以用多態
//List<Number> list2=new ArrayList<Integer>();//不可以這么做泛型參數類型不能用多態
List<Double> list2=new ArrayList<Double>();
List<? extends Number> list3=new ArrayList<Integer>();//泛型通配符,只能聲明引用,不能實例化對象
for(Number num:list3){//可以訪問對象
System.out.println(num);
}
//list3.add(5);//不能往加了通配符的泛型參數對象做任何修改,因為不能確定list3本來的類型是什么.
printList(list1);
printList(list2);
printList(list3);
}
public static void printList(List<? extends Number> list){
for(Number num:list){//可以訪問對象
System.out.println(num);
}
}
}
public class Test03 {
public static void main(String[] args){
Zoo<String> z=new Zoo<String>("hello");
String str=z.getName();
z.SetName("hehe");
System.out.println(str);
}
}
/*
* 自己寫一個帶泛型參數的類
*/
class Zoo<A>{//泛型標記是單個大寫字母
A name;
List<A> list;
//在類里的靜態方法里不能使用泛型參數
// public static void m1(A arg1){
//
// }
public Zoo(A name){
this.name=name;
}
public A getName(){
return name;
}
public void SetName(A name){
this.name =name;
}
}
/**
* 用反射驗證泛型是一個編譯時概念,
*/
import java.lang.reflect.*;
public class Test4 {
public static void main(String[] args) throws Exception{
HashSet <String> hs=new HashSet<String>();
hs.add("hello");
hs.add("hehe");
Class c=hs.getClass();
Method m=c.getMethod("add", Object.class);
m.invoke(hs, new Integer(5));
m.invoke(hs, new Double(3.14));
for(Object obj:hs){
System.out.println(obj);
}
}
}
/**
* 用反射驗證泛型是一個編譯時概念,
*/
import java.lang.reflect.*;
public class Test4 {
public static void main(String[] args) throws Exception{
HashSet <String> hs=new HashSet<String>();
hs.add("hello");
hs.add("hehe");
Class c=hs.getClass();
Method m=c.getMethod("add", Object.class);
m.invoke(hs, new Integer(5));
m.invoke(hs, new Double(3.14));
for(Object obj:hs){
System.out.println(obj);
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -