/*
每一个学生都有对应的归属地。
学生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练习!!!
最新推荐文章于 2022-07-13 00:57:01 发布
本文介绍了一种使用Java实现的学生信息存储方案,利用HashMap和TreeMap存储学生姓名、年龄及其对应的城市归属地。通过自定义Student类并重写equals、hashCode及compareTo方法确保了学生数据的唯一性和有序性。
摘要由CSDN通过智能技术生成