(集合) HashMap类

HashMap:是基于哈希表的Map接口实现。

目录

HashMap:是基于哈希表的Map接口实现。

例一:存储类型 HashMap<String,String>

例二:HashMap<Integer,String>

例三:HashMap<String,Student>

例四:存储类型HashMap<Student,String>(同例三)

LinkedHashMap:




 * 哈希表的作用是用来保证键的唯一性的。
 * 无序的

例一:存储类型 HashMap<String,String>

		// 创建集合对象
		HashMap<String, String> hm = new HashMap<String, String>();

		// 创建元素并添加元素
		// String key1 = "001";
		// String value1 = "jay";
		// hm.put(key1, value1);

		hm.put("001", "jay");
		hm.put("002", "tom");
		hm.put("003", "jason");

		// 遍历
		Set<String> set = hm.keySet();
		for (String key : set) {
			String value = hm.get(key);
			System.out.println(key + "---" + value);
		}

例二:存储类型HashMap<Integer,String>

		// 创建集合对象
		HashMap<Integer, String> hm = new HashMap<Integer, String>();

		// 创建元素并添加元素
		// Integer i = new Integer(27);
		// Integer i = 27;
		// String s = "jay";
		// hm.put(i, s);

		hm.put(27, "jay");
		hm.put(30, "tom");

		// 下面的写法是八进制,但是不能出现8以上的单个数据
		// hm.put(003, "hello");
		// hm.put(006, "hello");
		// hm.put(007, "hello");
		// hm.put(008, "hello");

		// 遍历
		Set<Integer> set = hm.keySet();
		for (Integer key : set) {
			String value = hm.get(key);
			System.out.println(key + "---" + value);
		}

		// 下面这种方式仅仅是集合的元素的字符串表示
		// System.out.println("hm:" + hm);

例三:存储类型HashMap<String,Student>

		// 创建集合对象
		HashMap<String, Student> hm = new HashMap<String, Student>();

		// 创建学生对象
		Student s1 = new Student("jay", 58);
		Student s2 = new Student("jj", 55);
		Student s3 = new Student("tom", 54);

		// 添加元素
		hm.put("9527", s1);
		hm.put("9522", s2);
		hm.put("9524", s3);

		// 遍历
		Set<String> set = hm.keySet();
		for (String key : set) {
			// String value = hm.get(key);
			Student value = hm.get(key);
			System.out.println(key + "---" + value.getName() + "---"
					+ value.getAge());
		}

例四:存储类型HashMap<Student,String>(同例三)

存储自定义对象想要去除元素的重复值,需要重写hashCode()方法和equals()方法;因为值的类型是Set保证了元素存储的唯一性。

        // 遍历
		Set<Student> set = hm.keySet();
		for (Student key : set) {
			String value = hm.get(key);
			System.out.println(key.getName() + "---" + key.getAge() + "---"
					+ value);
		}

LinkedHashMap:

是Map接口的哈希表和链接列表实现,具有可预知的迭代顺序。

 * 由哈希表保证键的唯一性
 * 由链表保证键盘的有序(存储和取出的顺序一致)

		// 创建集合对象
		LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();

		// 创建并添加元素
		hm.put("2345", "hello");
		hm.put("1234", "world");
		hm.put("3456", "java");
		hm.put("1234", "javaee");
		hm.put("3456", "android");

		// 遍历
		Set<String> set = hm.keySet();
		for (String key : set) {
			String value = hm.get(key);
			System.out.println(key + "---" + value);
		}

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值