HashMap的基本操作
< -- -- -- -- -- -- -- -- -- -- -- -- 创建学生类-- -- -- -- -- -- -- -- -- -- -- -- ->
public class Student implements Comparable < Student > {
private int age;
private String name;
private double score;
private int sno;
public Student ( ) {
}
public Student ( int age, String name, double score, int sno) {
this . age = age;
this . name = name;
this . score = score;
this . sno = sno;
}
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
this . age = age;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public double getScore ( ) {
return score;
}
public void setScore ( double score) {
this . score = score;
}
public int getSno ( ) {
return sno;
}
public void setSno ( int sno) {
this . sno = sno;
}
@Override
public int compareTo ( Student other) {
return this . sno - other. sno;
}
@Override
public boolean equals ( Object o) {
if ( this == o) return true ;
if ( o == null || getClass ( ) != o. getClass ( ) ) return false ;
Student student = ( Student ) o;
if ( age != student. age) return false ;
if ( Double . compare ( student. score, score) != 0 ) return false ;
if ( sno != student. sno) return false ;
return name != null ? name. equals ( student. name) : student. name == null ;
}
@Override
public int hashCode ( ) {
int result;
long temp;
result = age;
result = 31 * result + ( name != null ? name. hashCode ( ) : 0 ) ;
temp = Double . doubleToLongBits ( score) ;
result = 31 * result + ( int ) ( temp ^ ( temp >>> 32 ) ) ;
result = 31 * result + sno;
return result;
}
@Override
public String toString ( ) {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
", score=" + score +
", sno=" + sno +
'}' ;
}
}
< -- -- -- -- -- -- -- -- -- -- -- -- 创建测试类-- -- -- -- -- -- -- -- -- -- -- -- ->
import java. util. HashMap ;
import java. util. Iterator ;
import java. util. Map ;
import java. util. Set ;
public class TestMap2 {
public static void main ( String [ ] args) {
Map < Integer , Student > map = new HashMap < Integer , Student > ( ) ;
Student stu1 = new Student ( 20 , "张三" , 80 , 1 ) ;
Student stu2 = new Student ( 19 , "李四" , 81 , 2 ) ;
Student stu3 = new Student ( 18 , "王五" , 84 , 3 ) ;
Student stu4 = new Student ( 21 , "赵六" , 85 , 4 ) ;
Student stu5 = new Student ( 20 , "张三" , 80 , 1 ) ;
map. put ( stu1. getSno ( ) , stu1) ;
map. put ( stu2. getSno ( ) , stu2) ;
map. put ( stu3. getSno ( ) , stu3) ;
map. put ( stu4. getSno ( ) , stu4) ;
map. put ( stu5. getSno ( ) , stu5) ;
System . out. println ( map. get ( 3 ) ) ;
Set < Map. Entry < Integer , Student > > entryset = map. entrySet ( ) ;
Iterator < Map. Entry < Integer , Student > > it = entryset. iterator ( ) ;
while ( it. hasNext ( ) ) {
Map. Entry < Integer , Student > entry = it. next ( ) ;
Student stu = entry. getValue ( ) ;
System . out. println ( stu) ;
}
}
}