Java当中Map的认识和基本用法
生活随笔
收集整理的這篇文章主要介紹了
Java当中Map的认识和基本用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:Map
Map用于保存具有映射關系的數據,Map集合里保存著兩組值,一組用于保存Map的ley,另一組保存著Map的value,也就是Map的 鍵值 和關鍵值 。具體舉例 ,和查字典類似,通過key找到對應的value,通過頁數找到對應的信息。用學生類來說,key相當于學號,value對應name,age,sex等信息。用這種對應關系方便查找。
二:基礎了解
package cn.wyj.two;/*** Map是一個接口,我們平時多用它的實現類HashMap。* 實現類 也是 繼承 (繼承結口)*/import java.util.HashMap; import java.util.Map;public class Demo3_map {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubMap<Integer,String> m1 = new HashMap<Integer,String>();//這里需要用 HashMap 這是Map的實現類,//Map是接口不能new m1.put(1,"one");m1.put(2, "two");m1.put(3, "three");System.out.println(m1.get(2));System.out.println(m1.size());System.out.println(m1.isEmpty());System.out.println(m1.containsKey(1));//判斷容器當中是否含有此鍵值的元素System.out.println(m1.containsValue("four"));Map<Integer,String> m2 = new HashMap<Integer,String>();m2.put(4, "four");m2.put(5, "five");m2.putAll(m1);System.out.println(m2); }}三:進階碼(在一個類當中)
package cn.wyj.two;
import java.util.HashMap;
import java.util.Map;
public class Demo4_map2 {
/*** @param args*/ public static void main(String[] args) {// TODO Auto-generated method stubemployee e1 = new employee(1005, "王永杰", 50000);employee e2 = new employee(1002, "王二杰", 40000);employee e3 = new employee(1003, "王三杰", 30000);employee e4 = new employee(1001, "王四杰", 20000);Map<Integer,employee> m1 = new HashMap<Integer,employee>();m1.put(1005, e1);m1.put(1002, e2);m1.put(1003, e3);m1.put(1001, e4);employee emp = m1.get(1001);System.out.println("姓名:"+emp.getName()+",薪水:"+emp.getSlary());System.out.println(emp);//測試在Map容器當中不會有重復的元素,會直接將其覆蓋掉 }}
class employee{
private int id; private String name; private int slary; public employee(int id, String name, int slary) {super();this.id = id;this.name = name;this.slary = slary; } public int getId() {return id; } public void setId(int id) {this.id = id; } public String getName() {return name; } public void setName(String name) {this.name = name; } public int getSlary() {return slary; } public void setSlary(int slary) {this.slary = slary; }public String toString(){return "Id:" + this.id + " 姓名:" + this.name+" 薪水:" + this.slary; }}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Java当中Map的认识和基本用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 笔记本低压内存条和标压内存条的区别笔记本
- 下一篇: 2022年开学装机怎么配2022如何配电