处理方法
package test.MapDemo;
import java.util.*;
public class MapDemo4 {
public static void main(String[] args) {
Student s = new Student(12,"zhang");
Student s1 = new Student(15,"zhao");
Map<Integer,Student> stu = new HashMap<>();
//增
//key值是学生序号,value值是Student类的对象
stu.put(1,s);
stu.put(2,s1);
System.out.println(stu);
//查
//对比ss和s的地址值,发现结果为true,指向的是同一个对象
//可以通过ss获取age属性值
Student ss = stu.get(1);
System.out.println(ss == s);
System.out.println(ss.age);
//改
Student s2 = new Student(20,"chen");
stu.put(1,s2);
System.out.println(stu);
//删
stu.remove(1);
System.out.println(stu);
}
}
class Student{
public int age;
public String name;
public Student(int a,String n){
age = a;
name = n;
}
public String show(){
return name+"+"+age;
}
}
上面代码的运行结果为
四种遍历方法
package test.MapDemo;
import java.util.*;
public class MapDemo4 {
public static void main(String[] args) {
Student s = new Student(12,"zhang");
Student s1 = new Student(15,"zhao");
Map<Integer,Student> stu = new HashMap<>();
//增
stu.put(1,s);
stu.put(2,s1);
//遍历方法一
Set<Integer> keySet = stu.keySet();
Iterator<Integer> it1 = keySet.iterator();
while(it1.hasNext()){
Integer i = it1.next();
Student stu1 = stu.get(i);
System.out.println(i+"="+stu1.show());
}
//遍历方法二
Set<Map.Entry<Integer,Student>> entrySet = stu.entrySet();
Iterator<Map.Entry<Integer,Student>> it2 = entrySet.iterator();
while(it2.hasNext()){
Map.Entry<Integer,Student> entry = it2.next();
Integer key = entry.getKey();
Student value = entry.getValue();
System.out.println(key+"="+value.show());
}
//遍历方法三
for(Integer i : stu.keySet()){
Student stu2 = stu.get(i);
System.out.println(i+"="+stu2.show());
}
//遍历方法四
for(Map.Entry<Integer,Student> entry : stu.entrySet()){
Integer key = entry.getKey();
Student value = entry.getValue();
System.out.println(key+"="+value.show());
}
}
}
class Student{
public int age;
public String name;
public Student(int a,String n){
age = a;
name = n;
}
public String show(){
return name+"+"+age;
}
}
上面四种遍历的方法,输出的结果都是一样的