1)创建Student类,包含String类型的name,int类型的age,double类型的score,并重写getter、setter等方法。
2)创建5个Student对象。已知一个Integer类型的学号对应唯一的一个Student对象
3)将5个Student对象保存到HashMap容器中。
4)遍历该容器,打印出来。
package com.Work11;
import java.util.Objects;
/**
* @Author: 廾匸
* @Date: 2020/11/23 00:23
* @Description: 学生类
* @version: 1.01
*/
public class Student {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Double.compare(student.score, score) == 0 &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, score);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
package com.Work11;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @Author: 廾匸
* @Date: 2020/11/23 00:25
* @Description:
* @version: 1.01
*/
public class Tests {
@Test
public void test(){
Map<Integer,Student> map = new HashMap<>();
map.put(2,new Student("张三",26,98.7));
map.put(4,new Student("李四",24,99.3));
map.put(6,new Student("王五",28,98.4));
map.put(3,new Student("赵六",23,99.9));
map.put(5,new Student("田七",20,98.3));
Set<Map.Entry<Integer, Student>> entries = map.entrySet();
for (Map.Entry<Integer, Student> entry : entries) {
System.out.println(entry);
}
}
}