JAVA集合框架Map特性及實例解析
一Map特性:
1 Map提供一種映射關系,其中的元素是以鍵值對(key-value)的形式存儲的,能夠實現根據key快速查找value;
2 Map中鍵值對以Entry類型的對象實例形式存在;
3 鍵,即key不可重復,但是value值可以;
4 每個鍵最多只能映射一個值;
5 Map接口提供了分別返回key值集合、value值集合以及Entry(鍵值對)集合的方法;
6 Map支持泛型,形式如:Map<K,V>
二HashMap類:
1 HashMap是Map的一個重要實現類,也是最常用的,基于哈希表實現;
2 HashMap中的Entry對象是無序排列的;
3 Key值和Value值都可以為null,但是HashMap中只能有一個Key值為null的映射(key值不可重復);
示例:
package com.collection;import java.util.HashMap;import java.util.Set;import java.util.Scanner;public class MapTest { public HashMap<String,Student> students = new HashMap<String,Student>(); /* * 新建學生到Map中 * */ public void addStudent(){ //先添加三個學生 Scanner console = new Scanner(System.in); int i = 0; while(i<3){ System.out.println('請輸入學生ID:'); String id = console.next(); Student s = students.get(id); if(s == null){System.out.println('請輸入學生姓名:');String name = console.next();Student student = new Student(Integer.parseInt(id),name);students.put(id,student);System.out.println('添加了學生:'+student.id+'-'+student.name);i++; }else{System.out.println('該ID已經被占用');continue; } } } /* * 試用HashMap的keySet方法 * * 順便遍歷Students * */ public void forEachStudents(){ Set<String> ks = students.keySet(); System.out.println('共有學生數量'+students.size()+'個,具體如下:'); for(String key: ks){ Student student = students.get(key); if( student != null){System.out.println('學生ID:'+student.id+'-學生姓名:'+student.name); } } } public static void main(String[] args){ MapTest mt = new MapTest(); mt.addStudent(); mt.forEachStudents(); }}
其中Student類如下:
package com.collection;import java.util.HashSet;import java.util.Set;public class Student { public int id; public String name; //set中添加某個對象無論添加多少次,最終只會保留一個該對象(的引用),并且,保留的是第一次添加的那個 public Set<Course> course = new HashSet<Course>(); public Student(int id, String name){ this.id = id; this.name = name; }}
返回結果:
請輸入學生ID:請輸入學生姓名:劉備添加了學生:1-劉備請輸入學生ID:請輸入學生姓名:關羽添加了學生:2-關羽請輸入學生ID:請輸入學生姓名:張飛添加了學生:3-張飛共有學生數量3個,具體如下:學生ID:1-學生姓名:劉備學生ID:2-學生姓名:關羽學生ID:3-學生姓名:張飛
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
