且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java泛型

更新时间:2022-05-28 08:36:30

package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;

/*    泛型
 * 优点:通过允许指定泛型类或方法操作的类型,泛型功能将类型安全的任务从您转移给了编译器。
 * 不需要编写代码来测试数据类型是否正确,因为在编译时会强制使用正确的数据类型。
 * 减少了类型强制转换的需要和运行时错误的可能性。
 */
public class test{

	@Test
	public void test1() throws Exception{
		List<String> list = new ArrayList<String>();  //使用泛型 避免错误,更加安全
		list.add("aa");
		list.add("bb");
		list.add("cc");
	    for(String s:list){
	    	System.out.println(s);
	    }
	}	
	//使用泛形时,泛形类型须为引用类型,不能是基本数据类型
	@Test
	public void test2() throws Exception{
		Map<Integer,String> map = new HashMap<Integer,String>();  //使用泛型 避免错误,更加安全
		map.put(1,"aa");
		map.put(2,"bb");
		map.put(3,"cc");
		
	/*
	 * Set<Map.Entry<Integer, String>> set = map.entrySet();
	 * Iterator<Map.Entry<Integer, String>> it= set.iterator();
	   while(it.hasNext()){
		   Map.Entry<Integer, String> entry =it.next();
		   int key = entry.getKey();
		   String value = entry.getValue();
		   System.out.println(key+"="+value);
	   }*/
	   for(Map.Entry<Integer, String> entry : map.entrySet()){
		   int key=entry.getKey();
		   String value = entry.getValue();
		   System.out.println(key+"="+value);
	   }	   
	}
	//编写一个泛型方法 实现指定位置上的数组元素的交换。
	public static<T> void  swap1(T arr[],int pos1,int pos2){
		T temp = arr[pos1];
		arr[pos1] = arr[pos2];
		arr[pos2] = temp;
	}
	//编写一个泛型方法 接收一个任意数组 并颠倒数组中所有元素的位置
	public static <T> void swap2(T a[]){
		int start = 0;
		int end = a.length-1;
		while(start<end){
			T temp = a[start];
			a[start] = a[end];
			a[end] = temp;
			start++;
			end--;
		}
	}
	public static void main(String[] args){
		Integer a[]={1,2,3,4};
		Integer b[]={5,6,7,8};
		swap1(a,1,2);
		for(int i:a){
			System.out.println(i+" ");
		}
		swap2(b);
		for(int i:b){
			System.out.println(i+" ");
		}
	}	
}