1. 程式人生 > 其它 >Java案例——HashMap集合儲存學生物件並遍歷

Java案例——HashMap集合儲存學生物件並遍歷

一、需求:建立一個HashMap集合,鍵是學號(String),值是學生物件(Student),儲存三個鍵值對元素,並遍歷

分析:

1.定義學生類

2.建立HashMap集合物件

3.建立學生物件

4把學生新增到集合中

5.遍歷集合

public class StudentDemo {
  public static void main(String[] args) {
      //建立Map集合物件
      Map<String,Student> m=new HashMap<String,Student>();
      //新增鍵值對
      m.put("01",new Student("張三"));
      m.put("04",new Student("趙六"));
      m.put("02",new Student("李四"));
      m.put("03",new Student("王五"));
      //遍歷集合
      Set<Map.Entry<String,Student>> s= m.entrySet();
      //遍歷
      for (Map.Entry<String,Student> ss:s){
          //根據鍵值對物件獲取值和key
          String key=ss.getKey();
          Student value=ss.getValue();
          System.out.println(key+","+value.getName());
      }
      System.out.println("------------------------");
      //方式二,通過鍵找值
      Set<String> m1=m.keySet();
      for (String key :m1){
            Student student =m.get(key);
          System.out.println(key+","+student.getName());
      }
  }
}

二、需求:建立一個HashMap集合,鍵是學生物件(Student),值是地址(String),儲存三個鍵值對元素,並遍歷分析:

1.定義學生類

2.建立HashMap集合物件

3.建立學生物件,並把學生物件當作鍵值新增到集合

4把地址字串新增到集合中

5.為了保證資料的唯一性,需要在學生類中重寫hashCode及equals方法

6.遍歷集合

public class StudentDemo {
  public static void main(String[] args) {
      //建立集合物件
      Map<Student,String> m=new HashMap<Student,String>();
      //新增鍵值對
      m.put(new Student("張三",18),"上海");
      m.put(new Student("李四",19),"北京");
      m.put(new Student("王五",20),"上海");
      m.put(new Student("王五",20),"海南");
      //方式一
      //獲取所有鍵值對的集合
      Set<Map.Entry<Student,String>> s=m.entrySet();
      //方式一、遍歷
      for (Map.Entry<Student,String> mm:s){
          //通過鍵值對獲取對應的值與鍵
          Student key=mm.getKey();
          String value=mm.getValue();
          System.out.println(key.getName()+","+key.getAge()+value);
      }
      System.out.println("---------------------------------");
      //方式二
      Set<Student> key=m.keySet();
      for (Student s1:key){
          String value=m.get(s1);
          System.out.println(s1.getName()+","+s1.getAge()+","+value);
      }
  }
}