您的位置:首页 > 理论基础 > 数据结构算法

HashMap的两种取出方式keySet和entrySet

2016-07-14 22:36 447 查看
/*HashMap的两种取出方式keySet和entrySet
每一个学生都有对应的归属地。
学生Student,地址String.
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。

1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3.获取map集合中的元素。
*/
class Student implements Comparable<Student>//实现比较性< ? super E>
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Student s)//重写compareTo()方法
{
int num = new integer(this.age).compareTo(new Integer(s.age));//先比较age
if(num==0)
return this.name.compareTo(s.name);//再比较name
return num;
}
public int hashCode()//重写hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)//重写equals()
{
if (! (obj instanceof Student))
throw new ClassCastException("类型不匹配");//类型转换异常
Student s = (Student)obj;//强制转换类型
return this.name.equals(s.name) && this.age==s.age;//判断后存入Hash表
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
}
class MapTest
{
public static void main(String[] args)
{
System.out.println("Hello World!");

HashMap<Studengt,String> hm = new HashMap<Studengt,String>();

hm.put(hm.put(new Student("lisi1",21),"beijing"));//put(K key, V value)存入
hm.put(hm.put(new Student("lisi1",21),"tianjin"));
hm.put(hm.put(new Student("lisi2",22),"shanghai"));
hm.put(hm.put(new Student("lisi3",23),"nanjing"));
hm.put(hm.put(new Student("lisi4",24),"wuhan"));

//第一种取出方式 keySet

Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();

while(it.hasNext())
{
Student stu = it.next();
String addr = hm.get(stu);//传入值key,返回值是<k,v>里面的value
System.out.println(stu+"..."+addr);
}

//第二种取出方式entrySet
//Map.Entry是一种接口再实现内部接口
Set<Map.Entry<Student,String> entrySet = hm.next();
Iterator<Map.Entry<Student,String> iter = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String> me = iter.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+"..."+addr);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息