Map 與 HashMap的介紹
Map 增加元素實例
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MapTest {
/**
* 用來承裝學生類型對象
*/
public Map<String, Student> students;
/**
* 在構造器中初始化students 屬性
*/
public MapTest() {
this.students = new HashMap<String, Student>();
}
/**
* 測試添加:輸入學生ID
*/
public void testPut() {
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 newStudent = new Student(ID, name);
students.put(ID, newStudent);
System.out.println("成功添加學生:" + students.get(ID).name);
i++;
} else {
System.out.println("學生ID 被佔用");
continue;
}
}
}
/**
* 測試Map的keySet方法
* @param args
*/
public void testKeySet() {
// 通過keySet 方法,返回Map 中所有“鍵”的Set集合
Set<String> keySet = students.keySet();
// 取得students的容量
System.out.println("總共有:" + students.size() + "個學生!");
// 遍歷keySet,取得每一個鍵,再條用get() 方法取得每一個鍵對應的value
for (String stuId : keySet) {
Student st = students.get(stuId);
if (st != null) {
System.out.println("學生:" + st.name);
}
}
}
public static void main(String[] args) {
MapTest mt = new MapTest();
mt.testPut();
mt.testKeySet();
}
}
請輸入學生ID
1
請輸入學生姓名:
tom
成功添加學生:tom
請輸入學生ID
1
學生ID 被佔用
請輸入學生ID
2
請輸入學生姓名:
jack
成功添加學生:jack
請輸入學生ID
3
請輸入學生姓名:
xiadao
成功添加學生:xiadao
總共有:3個學生!
學生:tom
學生:jack
學生:xiadao
Map 刪除元素實例
/**
* 測試刪除Map 中的映射
*
* @param args
*/
public void testRemove() {
// 獲取從鍵盤輸入的待刪除學生ID 字符串
Scanner console = new Scanner(System.in);
while (true) {
// 提示輸入待刪除的學生ID
System.out.println("請輸入要刪除的學生ID");
String ID = console.next();
Student st = students.get(ID);
if (st == null) {
// 提示輸入的ID 不存在
System.out.println("該ID不存在");
continue;
}
students.remove(ID);
System.out.println("成功刪除學生:" + st.name);
break;
}
}
/**
* 通過 entrySet 方法遍歷Map
*
* @param args
*/
public void testEntrySet() {
// 通過entrySet 方法,返回Map中所有鍵值對
Set<Entry<String, Student>> entrySet = students.entrySet();
for (Entry<String, Student> entry : entrySet) {
System.out.println("取得鍵爲:" + entry.getKey());
System.out.println("對應的值爲:" + entry.getValue().name);
}
}
public static void main(String[] args) {
MapTest mt = new MapTest();
mt.testPut();
mt.testKeySet();
mt.testRemove();
mt.testEntrySet();
}
請輸入要刪除的學生ID
1
成功刪除學生:tom
取得鍵爲:2
對應的值爲:jack
取得鍵爲:3
對應的值爲:cat
Map修改元素實例
/**
* 利用put方法修改Map中已有的映射
*/
public void testModify(){
Scanner console = new Scanner(System.in);
while (true) {
System.out.println("請輸入要修改的學生ID");
String stuID=console.next();
Student student=students.get(stuID);
if (student==null) {
System.out.println("該ID不存在! 請重新輸入");
continue;
}
System.out.println("當前學生ID,所對應學生爲:"+student.name);
System.out.println("請重新輸入學生姓名:");
String name=console.next();
Student newStudent = new Student(stuID,name);
students.put(stuID, newStudent);
System.out.println("修改成功");
break;
}
}
請輸入要修改的學生ID
1
當前學生ID,所對應學生爲:q
請重新輸入學生姓名:
qq
修改成功