⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test01.java

📁 java5.0新增功能
💻 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 + -