创建一个Student类,然后再主函数里输出,查看效果
package com.moon.pojo;
import java.util.Objects;
/**
* @author moon
*/
public class Student {
private String name; //学生名
private int age; //年龄
//无参构造函数
public Student() {
}
//有参构造函数
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//get、set方法
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;
}
/* @Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}*/
}
Mian主函数代码
package com.moon;
import com.moon.pojo.Student;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
//创建Map集合对象
Map<String, Student> map = new HashMap<String,Student>();
//创建学生对象
Student student1 = new Student("小波",18);
Student student2 = new Student("小妤",18);
Student student3 = new Student("娜娜",18);
//添加学生对象到集合 map集合
map.put("150101",student1);
map.put("150102",student2);
map.put("150103",student3);
map.forEach((key,value) ->{
System.out.println(key + "-----" + value);
});
}
}
1、当没有写toString方法时
结果如下:
150103-----com.moon.pojo.Student@41629346
150101-----com.moon.pojo.Student@404b9385
150102-----com.moon.pojo.Student@6d311334
Process finished with exit code 0
我想输出的是Student类里的信息,但这显然不是我想要的,这好像是地址。
2、写toString方法,在Studeng类里吧toString方法加上,快捷键Alt+Ins(idea)
结果:
150103-----Student{name='娜娜', age=18}
150101-----Student{name='小波', age=18}
150102-----Student{name='小妤', age=18}
Process finished with exit code 0
这样是不是好看多了。