创建一个HashMap泛型对象,添加学员姓名分数,键为学员姓名值为学员对象,从HashMap中用迭代器打印学员成绩

2025-01-08 12:01:33
推荐回答(2个)
回答1:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Test {

public static void main(String args[]) {
Map students = new HashMap();
students.put("aaa", new Student(60));
students.put("bbb", new Student(70));
students.put("ccc", new Student(80));
for (Entry entry : students.entrySet()) {
System.out.println("姓名:" + entry.getKey() + " 成绩:" + entry.getValue());
}
}
}

class Student {

public Student(int point) {
this.point = point;
}

private int point;

public int getPoint() {
return point;
}

public void setPoint(int point) {
this.point = point;
}

@Override
public String toString() {
return String.valueOf(this.point);
}

}

回答2:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class TestHashMap {
public static void main(String[] args) {
Map map = new HashMap();
Student stu1 = new Student("张三",89);
Student stu2 = new Student("李四",90);
Student stu3 = new Student("王五",91);//姓名不要一样,不然被覆盖
map.put(stu1.getName(), stu1);
map.put(stu2.getName(), stu2);
map.put(stu3.getName(), stu3);
for(Iterator> it = map.entrySet().iterator(); it.hasNext();){
Entry entry = it.next();
System.out.println("姓名:"+entry.getKey()+" 成绩:"+entry.getValue().getScore());
}
}
}

class Student{
String name;
double score;
public Student(){

}
public Student(String name,double score){
this.name = name;
this.score = score;
}
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;
}

}