Map映射中獲取鍵值對的value值問題,報錯的地方,為什么value是一個Collection類而不是Set或者其他的?
package com.imooc.collection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class testMap {
/**
* 用來承裝學生類型對象
*/
public Map<String, Student> students;
public testMap(){
this.students=new HashMap<String,Student>();
}
/**
* 添加學生,并判斷是否被占用
*/
public void testPut(){
Scanner sc=new Scanner(System.in);
int i=0;
while(i<3){
System.out.println("請輸入第"+i+"學生姓名ID:");
String id=sc.nextLine();
Student stu=students.get(id);
if(stu==null){
//提示輸入姓名
System.out.println("請輸入第"+i+"學生姓名");
String name=sc.nextLine();
Student st=new Student(id, name);
students.put(id,st);
System.out.println("成功添加學生:"+students.get(id).name);
i++;
}else{
System.out.println("您輸入的ID已被占用,請重新輸入!");
continue;
}
}
}
/**
* 測試Map的ketSet方法
*/
public void testKeySet(){
System.out.println("總共有"+students.size()+"個學生!");
//通過keySet方法,返回Map中的所有“鍵”的set集合
Set<String> keySet=students.keySet();
// 遍歷keySet,取得每一個鍵,在調用get方法取得每個鍵對應的value
for(String stuid:keySet){
Student st=students.get(stuid);
if(st!=null)
System.out.println("學生:"+st.name);
}
}
/**
*?
* 測試刪除Map中的映射
* @param args
*/
public void testRemove(){
Scanner sc=new Scanner(System.in);
while(true){
System.out.println("請輸入要刪除的學生ID:");
String id=sc.nextLine();
//判斷id是否有對應的學生對象
Student st=students.get(id);
if(st==null){
System.out.println("該id不存在");
continue;
}else{
students.remove(id);
System.out.println("成功刪除學生:"+st.name);
break;
}
}
}
/**
* 通過entrySet方法遍歷Map
* @param args
*/
public void testEntrySet(){
Set<Entry<String,Student>> entrySet=students.entrySet();
for(Entry<String,Student> entry:entrySet){
System.out.println("取得鍵"+entry.getKey());
System.out.println("對應的值為"+entry.getValue().name);
}
}
/**
* 通過迭代器 分別遍歷students中的key和value
* @param args
*/
public void mapIterator(){
Set<String> set=students.keySet();
Iterator<String> it=set.iterator();
System.out.println();
System.out.println("key集合中的元素:");
while(it.hasNext()){
System.out.println(it.next());
}
Set<Student> col=students.values();
Collection<Student> coll=students.values();
Iterator<Student> iit=col.iterator();
System.out.println("Value集合中的元素:");
while(iit.hasNext()){
Student st=iit.next();
System.out.println("我是學生:"+st.id+",我的名字是:"+st.name);
}
}
public static void main(String[] args) {
testMap tm=new testMap();
tm.testPut();
tm.testKeySet();
tm.testRemove();
tm.testEntrySet();
tm.mapIterator();
}
}
2017-09-05
value是一個Collection類,Collection包含了:Set、List和Queue。他可以是Set也可以是List亦可以是Queue。程序中的value是Student,未用泛型規定其為Set或List類,就是默認的Collection類。當然你也可以用泛型規定value是指定類型類。例如:
Map<String,List<String>>?map=?new?HashMap<String,?List<String>>();
?List<String>?list=?new?ArrayList<String>();
2017-04-12
value值是可以重復的,key值是不可重復的,所以只有key值集合屬于Set集合
2017-03-19
Set是一種不包含重復的元素的Collection