Map练习!!!

本文介绍了一种使用Java实现的学生信息存储方案,利用HashMap和TreeMap存储学生姓名、年龄及其对应的城市归属地。通过自定义Student类并重写equals、hashCode及compareTo方法确保了学生数据的唯一性和有序性。

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

/*
每一个学生都有对应的归属地。
学生Student,地址String.
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
*/
import java.util.*;
class Student implements Comparable<Student>
{
	private String name;
	private int age;
	Student(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public void setAge(int age)
	{
		this.age=age;
	}
	public void setName(String name)
	{
		this.name=name;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	public int compareTo(Student s)
	{
		int num=new Integer(this.age).compareTo(new Integer(s.age));
		if (num==0)
		{
			return this.name.compareTo(s.name);
		}
		return num;
	}
	public boolean equals(Object obj)
	{
		if (!(obj instanceof Student))
		{
			throw new ClassCastException("类型不匹配!!!");
		}
		Student s=(Student)obj;
		return this.name.equals(s.name)&&this.age==s.age;
	}
	public int hashCode()
	{
		return this.name.hashCode()+age*39;
	}
}
class MapTest
{
	public static void main(String[] args)
	{
		HashMap<Student,String>hm=new HashMap<Student,String>();
		hm.put(new Student("xxc1",10),"hangzhou");
		hm.put(new Student("xxc2",20),"beijing");
		hm.put(new Student("xxc3",30),"chongqing");
		hm.put(new Student("xxc4",40),"zhongnanhai");
		//第一种取出方式,用keySet();
		Set<Student>keySet=hm.keySet();
		Iterator<Student> t=keySet.iterator();
		while (t.hasNext())
		{
			Student s=t.next();
			String s1=hm.get(s);
			System.out.println(s.getName()+"====="+s.getAge()+"=="+s1);
		}
		System.out.println("===================================================================");
		//第二种取出方式,用entrySet();
		Set<Map.Entry<Student,String>> me=hm.entrySet();
		Iterator<Map.Entry<Student,String>>t1=me.iterator();
		while (t1.hasNext())
		{
			Map.Entry<Student,String> me1=t1.next();
			Student s=me1.getKey();
			String s1=me1.getValue();
			System.out.println(s.getName()+"=="+s.getAge()+"=="+s1);
		}
	}
}
============================================================================================================
import java.util.*;
class TreeMapTest
{
	public static void main(String[] args)
	{
		TreeMap<Student,String>tm=new TreeMap<Student,String>(new MyCom());
		tm.put(new Student("xxc1",60),"hangzhou");
		tm.put(new Student("xxc5",10),"beijing");
		tm.put(new Student("xxc8",90),"chongqing");
		tm.put(new Student("xxc4",40),"zhongnanhai");
		Set<Map.Entry<Student,String>>entry=tm.entrySet();
		Iterator<Map.Entry<Student,String>> t=entry.iterator();
		while (t.hasNext())
		{
			Map.Entry<Student,String> me=t.next();
			Student s=me.getKey();
			String s1=me.getValue();
			System.out.println(s.getName()+"="+s.getAge()+"="+s1);
		}
	}
}
class MyCom implements Comparator<Student>
{
	public int compare(Student s1,Student s2)
	{
		int num=s1.getName().compareTo(s2.getName());
		if (num==0)
		{
			return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
		}
		return num;
	}
}
/*
用TreeMap集合对元素进行排序,方法和TreeSet一样!!!

*/

### 关于 Map 数据结构和函数的编程练习 Map 是一种常见的数据结构,在许多编程语言中有不同的实现形式,比如 Python 中的字典 (dictionary),C++ 的 `std::map` 和 Java 的 `HashMap`。以下是几个涉及 Map 数据结构或函数的经典编程练习题: #### 1. 字符串字符频率统计 编写一个程序来计算给定字符串中每个字符出现的次数并存储在一个映射表中。 ```python def char_frequency(s): freq_map = {} for c in s: if c not in freq_map: freq_map[c] = 0 freq_map[c] += 1 return freq_map result = char_frequency("hello world") print(result) # 输出 {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1} ``` 此代码片段展示了如何利用 map 来记录字符及其对应的频次[^1]。 #### 2. 单词计数器 设计一段代码用于读取文本文件中的单词,并创建一个 map 表示每个唯一单词以及它在整个文档中出现的次数。 ```python from collections import defaultdict def word_count(file_path): counts = defaultdict(int) with open(file_path, 'r') as file: for line in file: words = line.split() for word in words: counts[word.lower()] += 1 return dict(counts) counts_result = word_count('example.txt') print(counts_result) ``` 上述例子说明了通过遍历文件每一行并将每行拆分为单独词语的方式构建了一个基于默认字典的对象,默认字典会自动初始化不存在键值为零的情况[^2]。 #### 3. 反转键值对 假设有一个已存在的关联数组或者哈希表,请写一个方法用来交换所有的 key-value 对的位置形成新的反转后的集合。 ```python def invert_dict(original_dict): inverted = {value: key for key, value in original_dict.items()} return inverted original = {"apple": "fruit", "carrot": "vegetable"} inverted = invert_dict(original) print(inverted) # 输出 {'fruit': 'apple', 'vegetable': 'carrot'} ``` 这里提供了一种简洁的方法去完成这个任务——借助推导式语法快速生成一个新的倒置版本的地图对象[^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值