Java中,泛型在集合中的使用

泛型
作为一个标识,来规范参数的类型。
在编译时就会进行类型检测

泛型的使用:
1.泛型的类型必须是类,不能是基本数据类型,要使用对应的包装类
2.泛型的类型作为一个标识,来规范参数的类型
3.实例化是没有指明泛型的类型,默认为Object

代码举例:

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

public class Test {
	public static void main(String[] args) {
		System.out.println("以ArrayList为例:");
		Test test = new Test();
		test.test();
		System.out.println("\n以HashMap为例:");
		test.test2();
	}
	
	public void test() {
		//给ArrayList加上泛型Integer(包装类),保证存储的数据必须是Integer
		ArrayList<Integer> arrayList = new ArrayList<>();
		arrayList.add(12);
//		arrayList.add("hello"); 报错,因为泛型为Integer
		arrayList.add(30);
		arrayList.add(25);
		
		//使用foreach
		for (Integer integer : arrayList) {
			System.out.println(integer);
			
		}
		//使用迭代器Iterator
		System.out.println("-------------");
		Iterator<Integer> iterator = arrayList.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}
	
	public void test2() {
		//指定key为String,value为Integer
		HashMap<String, Integer> hashMap = new HashMap<>();
		hashMap.put("age", 18);
		hashMap.put("class", 1);
		hashMap.put("score", 100);
		
		//使用迭代器(Iterator)遍历
		Set<Entry<String, Integer>> entrySet2 = hashMap.entrySet();
		Iterator<Entry<String, Integer>> iterator = entrySet2.iterator();
		while(iterator.hasNext()) {
//			System.out.println(iterator.next());
			Entry<String, Integer> next = iterator.next();
			String key = next.getKey();
			Integer value = next.getValue();
			System.out.println(key+" ---- "+value);
		}
		
		System.out.println("---------------");
		
		//使用foreach遍历
		Set<Entry<String, Integer>> entrySet = hashMap.entrySet(); //获取键值对组成的集合set
		for (Entry<String, Integer> entry : entrySet) {
			System.out.println(entry);
		}
	}
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值