泛型:在集合中使用泛型的场景

在集合中使用泛型的场景

//2.在集合中使用泛型的场景
@Test
public void test2() {
	
	//1.List使用泛型
	List<Integer> list = new ArrayList<Integer>();
	list.add(75);
	list.add(85);
	list.add(95);
	//list.add("AA"); 会报编译错误,只能添加Integer类型数据
	//第1种遍历List的方式
	for(int i=0; i<list.size(); i++) {
		int score = list.get(i);
		//输出:75 85 95
		System.out.print(score + " ");
	}
	//第2种遍历List的方式
	Iterator<Integer> iter = list.iterator();
	while(iter.hasNext()) {
		int score = iter.next();
		//输出:75 85 95
		System.out.print(score + " ");
	}
	
	//2.Map使用泛型
	Map<String,Integer> map = new HashMap<String,Integer>();
	map.put("AA", 75);
	map.put("BB", 85);
	map.put("CC", 95);
	//遍历Map中的数据
	Set<Entry<String,Integer>> set = map.entrySet();
	for(Entry<String,Integer> entry:set) {
		String key = entry.getKey();
		int value = entry.getValue();
		//输出:AA===75
		//    BB===85
		//	  CC===95
		System.out.println(key + "===" + value);
	}
}

猜你喜欢

转载自lipiaoshui2015.iteye.com/blog/2264304