//HashMap: 底层是哈希表数据结构,允许使用null键或值,线程不同步
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 setName(String name)
{
this.name=name;
}
public void setAge(int Age)
{
this.age=age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public String toString()
{
return name+":"+age;
}
public int hashCode()
{
return name.hashCode()+this.age*23;
}
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 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;
}
}
class HashMapTest
{
public static void main(String[] args){
HashMap<Student,String> hm=new HashMap<Student,String>() ;
hm.put(new Student("test1",21),"beijing"); //新增元素
hm.put(new Student("test2",22),"nanjing");
hm.put(new Student("test3",23),"shanghai");
hm.put(new Student("test4",24),"hangzhou");
//map 第一种取出方式:keySet
Set<Student> keyset =hm.keySet();
Iterator<Student> it=keyset.iterator();
while(it.hasNext())
{
Student stu= it.next();
String addr=hm.get(stu);
System.out.println(stu+" "+addr);
}
//map 第二种取出方式:entrySet
Set<Map.Entry<Student,String>> mapentry = hm.entrySet();
Iterator<Map.Entry<Student,String>> itr=mapentry.iterator();
while(itr.hasNext())
{
Map.Entry<Student,String> me= itr.next();
Student s = me.getKey();
String addr = me.getValue();
System.out.println(s+" "+addr);
}
}
}
Java - HashMap
最新推荐文章于 2024-07-13 13:55:40 发布