Map用法
阿新 • • 發佈:2019-02-25
hash spa con student ack static image bsp this
學生類
package com.job_2_22; /** * 學生類 * @author Administrator * */ public class Student { /** * 學生屬性 */ private String name; private char sex; /** * 構造方法 */ public Student() {} public Student(String name, char sex) { super();this.name = name; this.sex = sex; } /** * setter getter */ public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public voidsetSex(char sex) { this.sex = sex; } }
學生測試類
package com.job_2_22; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * 學生測試類 * @author Administrator * */ public class StudentTest { public static void main(String[] args) {//創建map學生類的集合 key value 無序 唯一 Map<String,Student> student=new HashMap<String,Student>(); //創建學生對象 Student s1=new Student("張三",‘男‘); Student s2=new Student("李四",‘男‘); Student s3=new Student("王五",‘男‘); Student s4=new Student("小劉",‘女‘); //把學生放入map學生類集合 key value student.put("zs", s1); student.put("ls", s2); student.put("ww", s3); student.put("xl", s4); //遍歷所有值 for(Student stu:student.values()) { //用values對象,遍歷出所有對象 System.out.print(stu.getName()+"\t"); System.out.println(stu.getSex()); } //遍歷所有鍵 System.out.println("keySet遍歷所有鍵:"+student.keySet()); //get用鍵獲取值 System.out.println("get用鍵獲取值:"+student.get("ww").getName()+student.get("ww").getSex()); //remove刪除這個鍵 student.remove("xl"); //containsKey判斷是否存在這個鍵,返回boolean類型 System.out.println("containsKey判斷是否存在這個鍵“ww”:"+student.containsKey("ww")); System.out.println("containsKey判斷是否存在這個鍵“ss”:"+student.containsKey("ss")); //contains Value判斷是否有這個值 System.out.println("contains Value判斷是否存在這個鍵“s1”:"+student.containsValue(s1)); System.out.println("contains Value判斷是否存在這個鍵“s4”:"+student.containsValue(s4)); //keySet System.out.println("獲取所有key:"+student.keySet()); //value System.out.println("獲取所有value:"+student.values()); //遍歷出所有鍵 for(String s:student.keySet()) { System.out.println(s); } //遍歷出所有值 for(Student s:student.values()) { System.out.println(s.getName()+s.getSex()); } //分別遍歷 map中的鍵和值 for(String s:student.keySet()) { System.out.println("鍵:"+s+",值:"+student.get(s).getName()+student.get(s).getSex()); } //Iterator叠代器拿到每個key Iterator<String> itor=student.keySet().iterator(); //把map所有鍵放入叠代器 while(itor.hasNext()) { //判斷叠代器裏是否有下個值 String key=(String)itor.next(); //叠代器轉成賦值給key String name=student.get(key).getName(); //key找到value對象的name char sex=student.get(key).getSex(); //key找到value對象的sex System.out.println("叠代器輸出:"+name+sex); //輸出name 和 sex } //map.entry for(Map.Entry<String, Student> m:student.entrySet()) { String key=m.getKey(); //Map.Entry類型獲取key Student s=m.getValue(); //Map.Entry類型獲取value String name=s.getName(); //value獲取name char sex=s.getSex(); //value獲取sex System.out.println("key:"+key+",value"+name+"-"+sex); } // } }
運行
Map用法