public class Main { public static void main(String[] args) { Map<String,Student>hashMap=new HashMap<>(); Student student=new Student("赵同学",30); Student student1=new Student("孙同学",18); Student student2=new Student("康同学",32); hashMap.put("赵同学",student); hashMap.put("孙同学",student1); hashMap.put("康同学",student2); System.out.println(hashMap); } } class Student { private String name; private int number; private Map<String,Integer>hashMap; private Map<String,Integer>hashMap1; public Student(String name,int number) { this.name=name; this.number=number; } public void putInfo(String key,String value) { } public String getName() { return name; } public int getNumber() { return number; } }这段代码想要输出信息应该如何更改
时间: 2024-01-17 18:06:17 浏览: 134
如果想要输出学生的姓名和学号,可以在Student类中添加toString方法,如下:
```
class Student {
private String name;
private int number;
private Map<String,Integer>hashMap;
private Map<String,Integer>hashMap1;
public Student(String name,int number)
{
this.name=name;
this.number=number;
}
public void putInfo(String key,String value) {
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
@Override
public String toString() {
return "name: " + name + ", number: " + number;
}
}
```
然后在Main类中调用HashMap的toString方法即可输出每个学生的姓名和学号:
```
public static void main(String[] args) {
Map<String,Student>hashMap=new HashMap<>();
Student student=new Student("赵同学",30);
Student student1=new Student("孙同学",18);
Student student2=new Student("康同学",32);
hashMap.put("赵同学",student);
hashMap.put("孙同学",student1);
hashMap.put("康同学",student2);
System.out.println(hashMap.toString());
}
```
输出结果为:
```
{赵同学=name: 赵同学, number: 30, 孙同学=name: 孙同学, number: 18, 康同学=name: 康同学, number: 32}
```
阅读全文