黑马程序员技术交流社区
标题:
听课时,感觉很经典的一道题。复习还是很有用的
[打印本页]
作者:
nerveva2000
时间:
2014-10-16 19:53
标题:
听课时,感觉很经典的一道题。复习还是很有用的
/*
没个学生都有自己的归属地
学生Student 地址 String
学生属性, 姓名 年龄
注意: 姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
1描述学生
2定义map容器,将学生作为键,地址作为值,存入
3获取map集合中的元素
*/
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi2",22),"beijing");
hm.put(new Student("lisi3",23),"nanjing");
hm.put(new Student("lisi4",24),"wuhan");
//第一种取出方式
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext())
{
Student stu = it.next();
String addr = hm.get(stu);
sop(stu+"--"+addr);
}
//第二种取出方式
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> it1 = entrySet.iterator();
while(it1.hasNext())
{
Map.Entry<Student,String> me=it1.next();
Student s = me.getKey();
String str = me.getValue();
sop(s+"----"+str);
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
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 s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));
if (num ==0)
return this.name.compareTo(s.name);
return num;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+"--"+age;
}
}
复制代码
作者:
☆枫の云
时间:
2014-10-17 21:37
确实是基础的经典,支持一下
作者:
chen578157939
时间:
2014-10-18 10:41
非常的棒哦
作者:
new999
时间:
2014-10-18 12:05
遍历MAP的两种方式,覆写JavaBean中的hasCode、equals方法,保证唯一,覆写compareTo方法,保证具有比较性
作者:
张周飞
时间:
2014-10-18 14:26
收藏了
!!!!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2