Java集合——HashMap和Hashtable应用实例

本文探讨了Java中HashMap和Hashtable的应用,详细解释了当在HashMap的同一Key上添加不同Object时,如何发生覆盖现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.shuzu;

import java.util.HashMap;
import java.util.Iterator;

public class HashMapTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student s1 = new Student("小明",25);
		Student s2 = new Student("小刚",24);
		Student s3 = new Student("小胖",23);
		
		HashMap hm = new HashMap();
		hm.put("小明", s1);
		hm.put("小刚", s2);
		hm.put("小强", s3);
		
		//1.取出信息
		if(hm.containsKey("小明")){
			System.out.println("有该学生!");
			Student st = (Student) hm.get("小明");
			System.out.println("姓名:"+st.getName()+"  年龄:"+st.getAge());
		}else {
			System.out.println("没有该学生!");
		}
		
		//2.利用 Iterator ,遍历 HashMap
		Iterator it = hm.keySet().iterator();
		while(it.hasNext()){
			String key = it.next().toString();
			//上一步得到 “Key”,现在取出对象
			Student st = (Student) hm.get(key);
			System.out.println("找到学生:"+st.getName()+" 年龄:"+st.getAge());
		}
	}
}

class Student{
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	private int age;
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
}

注意:

1、HashMap 如果在同一个“Key“上添加不同的”object“,HM会默认后者 覆盖前者。

                hm.put("小明", s1);
		hm.put("小刚", s2);
		hm.put("小明", s3);

  如上Code,第三行s3将覆盖s1 。
  即HashMap中的Key,Value是一一对应的关系。


2、遍历HashMap 时使用 Iterator 。
3、HashMap在遍历时,并不是按照添加的前后顺序输出的!
      输出顺序到底是什么规律呢?

4、Hashtable 与HashMap 在使用的”存取、遍历“等方法上几乎一致!!  其区别主要在于”线程同步“与否。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值