久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

JAVA集合框架Map特性及實(shí)例解析

瀏覽:101日期:2022-09-03 11:24:41

一Map特性:

1 Map提供一種映射關(guān)系,其中的元素是以鍵值對(key-value)的形式存儲(chǔ)的,能夠?qū)崿F(xiàn)根據(jù)key快速查找value;

2 Map中鍵值對以Entry類型的對象實(shí)例形式存在;

3 鍵,即key不可重復(fù),但是value值可以;

4 每個(gè)鍵最多只能映射一個(gè)值;

5 Map接口提供了分別返回key值集合、value值集合以及Entry(鍵值對)集合的方法;

6 Map支持泛型,形式如:Map<K,V>

二HashMap類:

1 HashMap是Map的一個(gè)重要實(shí)現(xiàn)類,也是最常用的,基于哈希表實(shí)現(xiàn);

2 HashMap中的Entry對象是無序排列的;

3 Key值和Value值都可以為null,但是HashMap中只能有一個(gè)Key值為null的映射(key值不可重復(fù));

示例:

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>(); /* * 新建學(xué)生到Map中 * */ public void addStudent(){ //先添加三個(gè)學(xué)生 Scanner console = new Scanner(System.in); int i = 0; while(i<3){ System.out.println('請輸入學(xué)生ID:'); String id = console.next(); Student s = students.get(id); if(s == null){System.out.println('請輸入學(xué)生姓名:');String name = console.next();Student student = new Student(Integer.parseInt(id),name);students.put(id,student);System.out.println('添加了學(xué)生:'+student.id+'-'+student.name);i++; }else{System.out.println('該ID已經(jīng)被占用');continue; } } } /* * 試用HashMap的keySet方法 * * 順便遍歷Students * */ public void forEachStudents(){ Set<String> ks = students.keySet(); System.out.println('共有學(xué)生數(shù)量'+students.size()+'個(gè),具體如下:'); for(String key: ks){ Student student = students.get(key); if( student != null){System.out.println('學(xué)生ID:'+student.id+'-學(xué)生姓名:'+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中添加某個(gè)對象無論添加多少次,最終只會(huì)保留一個(gè)該對象(的引用),并且,保留的是第一次添加的那個(gè) public Set<Course> course = new HashSet<Course>(); public Student(int id, String name){ this.id = id; this.name = name; }}

返回結(jié)果:

請輸入學(xué)生ID:請輸入學(xué)生姓名:劉備添加了學(xué)生:1-劉備請輸入學(xué)生ID:請輸入學(xué)生姓名:關(guān)羽添加了學(xué)生:2-關(guān)羽請輸入學(xué)生ID:請輸入學(xué)生姓名:張飛添加了學(xué)生:3-張飛共有學(xué)生數(shù)量3個(gè),具體如下:學(xué)生ID:1-學(xué)生姓名:劉備學(xué)生ID:2-學(xué)生姓名:關(guān)羽學(xué)生ID:3-學(xué)生姓名:張飛

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 阳信县| 彰化县| 南阳市| 铜川市| 牟定县| 临洮县| 巨鹿县| 丰原市| 息烽县| 遂平县| 来安县| 扬中市| 噶尔县| 永兴县| 锡林浩特市| 信阳市| 乌鲁木齐县| 留坝县| 东明县| 遂溪县| 于田县| 故城县| 长海县| 建宁县| 宁陵县| 寿宁县| 渑池县| 资源县| 贵州省| 平原县| 陆川县| 东阿县| 密山市| 舟曲县| 乌拉特前旗| 盘锦市| 中超| 萨嘎县| 通州市| 女性| 嘉兴市|