Java Collection和Map使用泛型

圖一:

圖二:

示例代碼:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

public class TestE {
	//不使用泛型,取元素需要強轉
	@Test
	public void test1() {
		List list = new ArrayList();
		list.add(123);
		list.add(34);
		list.add(534);
		list.add(1244);
		list.add(75);
		list.add(8);
		list.add(23);
		
		for (Object object : list) {
			int num = (Integer) object;//強轉然後拆包
			System.out.println(num);
		}
	}
	
	//使用泛型,不用強轉
	@Test
	public void test2() {
		List<Integer> list = new ArrayList<Integer>();
		list.add(123);
		list.add(34);
		list.add(534);
		list.add(1244);
		list.add(75);
		list.add(8);
		list.add(23);
		
		for (Integer integer : list) {
			int num = integer;
			System.out.println(num);
		}
	}
	
	@Test
	public void test3() {
		Map<String,Integer> map = new HashMap<String, Integer>();
		map.put("AA", 11);
		map.put("BB", 22);
		map.put("CC", 33);
		map.put("DD", 44);
		map.put("EE", 55);
		map.put("FF", 66);
		map.put("GG", 77);
		map.put("HH", 88);
		
		Set<Entry<String, Integer>> set = map.entrySet();
		for (Entry<String, Integer> entry : set) {
			Map.Entry<String, Integer> e = entry;
			System.out.println(e);
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章