生活随笔
收集整理的這篇文章主要介紹了
mooc_java 集合框架中 学生所选课程2MapHashMap
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Map&HashMap
Map提供映射關系,元素以鍵值對形式存儲,Map的鍵值對一Entry類型的對象實例形式存在,key值不能重復,value可以
鍵最多能映射到一個值,支持泛型 Map<K,V>
HashMap是Map的一個重要實現類,基于哈希表實現,其中的Entry對象是無序排列的,key和value值都可以為null,但只能有一個key值為null的映射(key值不可以重復)
public class MapTest {/*** 承裝學生類型對象*/public Map<String, Student>
students;public MapTest(){this.students=
new HashMap<String,Student>
();}/*** 測試添加:輸入學生Id,判斷是否被占用* 若為被占用,則輸入姓名,創建學生對象,并且添加到students中* @param args*/public void testPut(){//創建Scanner對象,用來獲取輸入的學生ID和姓名Scanner console=
new Scanner(System.in);int i=0
;while(i<3
){System.out.println("請輸入學生ID"
);String ID=
console.next();//判斷ID是否被占用Student st=
students.get(ID);if(st==
null){System.out.println("請輸入學生姓名:"
);String name=
console.next();Student news=
new Student(ID, name);//調用students的put方法,添加ID-學生映射
students.put(ID,news);System.out.println("成功添加學生:"+
students.get(ID).name); i++
;}else{System.out.println("該學生ID已被占用"
);continue;}}}/*** 測試Map的keySet方法* @param args*/public void testKeySet(){//已經規定泛型為String類型Set<String> ks=
students.keySet();//取得students的容量System.out.println("總共有:"+students.size()+"個學生"
);//遍歷KeySet,取得每一個鍵,再調用個體方法取得每個鍵對應的valuefor(String stuId:ks){Student st=
students.get(stuId);if(st!=
null)System.out.println("學生:"+
st.name);}}/*** 測試刪除Map中的映射* @param args*/public void testRemove(){//獲取從鍵盤輸入的待刪除學生ID字符串Scanner console=
new Scanner(System.in);while(
true){System.out.println("輸入要刪除的學生ID"
);String stuID=
console.next();//判斷是否有對應的學生對象Student st=
students.get(stuID);if(st==
null){//提示輸入的ID并不存在System.out.println("該ID不存在"
);continue;}students.remove(stuID);System.out.println("成功刪除學生"+
st.name);break;}}/*** 通過entrySet方法來遍歷Map*/public void testEntrySet(){//entrySet方法返回Map的所有鍵值對//Set<Entry> es=students.entrySet();Set<Entry<String,Student>> es=
students.entrySet();for(Entry<String,Student>
entry:es){System.out.println("取得鍵為:"+
entry.getKey());System.out.println("值為為:"+
entry.getValue().name); }}/*** put方法修改Map中 已有的映射* @param args*/public void testModify(){System.out.println("請輸入要修改的學生的ID:"
);Scanner console=
new Scanner(System.in);while(
true){String stuID=
console.next();//判斷是否有對應的學生對象Student st=
students.get(stuID);if(st==
null){//提示輸入的ID并不存在System.out.println("該ID不存在"
);continue;}else{System.out.println("當前學生ID對應:"+
st.name);System.out.println("請輸入新的學生姓名 :"
);String name=
console.next();Student ns=
new Student(stuID, name);students.put(stuID, st);System.out.println("修改成功"
);break;}}}public static void main(String[] args) {MapTest mt=
new MapTest();mt.testPut();mt.testKeySet();mt.testRemove();mt.testEntrySet();mt.testModify();mt.testEntrySet();}} ?
轉載于:https://www.cnblogs.com/mao-19/p/4961684.html
總結
以上是生活随笔為你收集整理的mooc_java 集合框架中 学生所选课程2MapHashMap的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。