黑马程序员技术交流社区
标题:
HashMap自定义对象练习一(解法一)
[打印本页]
作者:
itheima_llt
时间:
2015-4-18 20:14
标题:
HashMap自定义对象练习一(解法一)
每一个学生都有对应的归属地。
学生Student,地址String。
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
思路
1 把学生属性存入学生对象--抽象出学生类
2 创建容器,把学生对象存入容器
3 取出学生和对应地址
在学生类中需要做的事:
1 因为要存入多个学生对象进容器,所以必须让学生具备比较性,或者实现比较器
2 因为要去除重复元素,所以一定要覆盖hashCode和equals方法--哈希表计算哈希地址再比较内容
3 set,get,toString方法必须写
4 对于不是学生对象应该抛出异常
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 int compareTo(Student stu)
{
//按学生的年龄排序,如果年龄相等就按姓名字典序排序
int num = new Integer(this.getAge()).compareTo(new Integer(stu.getAge()));
if(num == 0)
return this.getName().compareTo(stu.getName());
//否则就按年龄排序
return num;
}
//计算学生对象的哈希地址
public int hashCode()
{
return name.hashCode()+age*37;
}
public boolean equals(Object obj)
{
//如果不是学生对象,抛出类型转换异常
if(!(obj instanceof Student))
throw new ClassCastException("不能转换成Student类型");
//类型转换
Student stu = (Student)obj;
//比较学生对象姓名和年龄,去除重复元素
return this.getName().equals(stu.getName()) && this.getAge()==stu.getAge();
}
public void setName(String name)
{
this.name =name;
}
public String getName()
{
return name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+"....."+age;
}
}
//主类用public修饰
public class MapTest
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
//1 创建hashMap映射
HashMap<Student,String> hm = new HashMap<Student,String>();
//2 添加学生对象为键和对应的地址为值
hm.put(new Student("Jack",20),"北京");
hm.put(new Student("mike",19),"兰州");
hm.put(new Student("mike",19),"兰州");
hm.put(new Student("Tom",25),"广州");
hm.put(new Student("Alice",17),"上海");
hm.put(new Student("Jimmy",21),"长沙");
//3 取出学生和对应地址
getWay(hm);
}
//3.1用第一种方式从Map中取出所有键值
public static void getWay(HashMap<Student,String> hm)
{
sop("用第一种方式从Map中取出所有键值:");
//1 把所有的键存入Set
Set<Student> keySet = hm.keySet();
//2 keySet获取迭代器
for(Iterator<Student> it = keySet.iterator(); it.hasNext(); )
{
//3 迭代取出键,用get获取对应值
Student stu = it.next();
String addr = hm.get(stu);
//4 打印取出的结果
sop(stu.toString()+"......"+addr);
}
}
}
复制代码
第一种方式.jpg
(51.26 KB, 下载次数: 0)
下载附件
2015-4-18 20:14 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2