(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
public class Student {
String name;
int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
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 + "]";
}
}
(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
public static void main(String[] args){
Map<Student, String> map = new HashMap<>();
inputMap(map);
bianli01(map);
bianli02(map);
}
public static void inputMap(Map<Student, String> map) {
Student stu = new Student();
stu.setName("wang");
stu.setAge(23);
map.put(stu, "beijing");
Student stu1 = new Student();
stu1.setName("zhao");
stu1.setAge(22);
map.put(stu1, "shanxi");
Student stu2 = new Student();
stu2.setName("liu");
stu2.setAge(19);
map.put(stu2, "fujian");
}
(3)利用四种方式遍历Map集合中的内容,格式:key::value
public static void bianli02(Map<Student, String> map) {
Set<Entry<Student, String>> entrySet = map.entrySet();
for(Entry<Student, String> entry : entrySet){
System.out.println(entry.getKey()+"::"+entry.getValue());
}
}
public static void bianli01(Map<Student, String> map) {
Set<Student> set = map.keySet();
for(Student student: set){
System.out.println(student+"::"+map.get(student));
}
}