⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hashmaptest.java

📁 编程之道--java程序设计入门源代码
💻 JAVA
字号:
/**
 * 通过这个程序,测试散列映像的存储与遍历,方法的使用
 */
import java.util.HashMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

public class HashMapTest
{
	public static void main(String[] args)
	{
		HashMap map = new HashMap();
		HashMapTest test  = new HashMapTest();
		//生成三个学生实例
		Student tom = new Student("Tom","20020410");
		Student jack = new Student("Jack","20020411");
		Student smith = new Student("Smith","20020412");
		
		map.put("one", tom);
		map.put("two", jack);
		map.put("three", smith);
		
		System.out.println("现在映像中元素的个数是:" + map.size() + "\n");
		
		Set key = map.keySet();//得到关键字的集合
		System.out.println("现在映像中的关键字分别是:");
		Iterator iterKey = key.iterator();
		while(iterKey.hasNext())
		{
			System.out.println(iterKey.next());
		}
		test.getValue(map);
		
		System.out.println("\n现在设置重复关键字,覆盖原来的对象。\n");
		Student rose = new Student("Rose","20020413");
		System.out.println("覆盖已经存在的关键字时返回值:" + map.put("two", rose));
		test.getValue(map);
	}
	
	public void getValue(HashMap map)
	{
		Collection values = map.values();//得到值的集合
		System.out.println("\n现在映像中的值分别是:");
		Iterator iterValue = values.iterator();
		while(iterValue.hasNext())
		{
			System.out.println(iterValue.next());
		}
	}
}

/**
 * 我们设计的学生基本类
 */
class Student
{
	private String strName = "";//学生姓名
	private String strNumber = "";//学号
	private String strSex = "";//性别
	private String strBirthday = "";//出生年月
	private String strSpeciality = "";//专业
	private String strAddress = "";//地址

	public Student(String name, String number)
	{
		strName = name;
		strNumber = number;
	}

	public String getStudentName()
	{
		return strName;
	}

	public String getStudentNumber()
	{
		return strNumber;
	}

	public void setStudentSex(String sex)
	{
		strSex = sex;
	}

	public String getStudentSex()
	{
		return strSex;
	}

	public String getStudentBirthday()
		{
		return strBirthday;
	}

	public void setStudentBirthday(String birthday)
	{
		strBirthday = birthday;
	}

	public String getStudentSpeciality()
	{
		return strSpeciality;
	}

	public void setStudentSpeciality(String speciality)
	{
		strSpeciality = speciality;
	}

	public String getStudentAddress()
	{
		return strAddress;
	}

	public void setStudentAddress(String address)
	{
		strAddress = address;
	}

	public String toString()
	{
		String information = "学生姓名=" + strName + ", 学号=" + strNumber;  
		if( !strSex.equals("") )
			information += ", 性别=" + strSex;
		if( !strBirthday.equals(""))
			information += ", 出生年月=" + strBirthday;
		if( !strSpeciality.equals("") )
			information += ", 专业=" + strSpeciality;
		if( !strAddress.equals("") )
			information += ", 籍贯=" + strAddress;
		return information;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -