Java从零开始学二十三(集合Map接口)
生活随笔
收集整理的這篇文章主要介紹了
Java从零开始学二十三(集合Map接口)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、Map接口
Collection、Set、List接口都屬于單值的操作,即:每次只能操作一個對象,而Map與它們不同的是,每次操作的是一對對象,即二元偶對象,Map中的每個元素都使用key à value的形式存儲在集合之中二、常用方法
| No. | 方法或類 | 類型 | 描述 |
| 1 | public void clear() | 普通 | 清空Map集合 |
| 2 | public boolean containsKey(Object key) | 普通 | 判斷指定的key是否存在 |
| 3 | public boolean containsValue(Object value) | 普通 | 判斷指定的value是否存在 |
| 4 | public Set<Map.Entry<K,V>> entrySet() | 普通 | 將Map對象變為Set集合 |
| 5 | public boolean equals(Object o) | 普通 | 對象比較 |
| 6 | public V get(Object key) | 普通 | 根據key取得value |
| 7 | public int hashCode() | 普通 | 返回哈希碼 |
| 8 | public boolean isEmpty() | 普通 | 判斷集合是否為空 |
| 9 | public Set<K> keySet() | 普通 | 取得所有的key |
| 10 | public V put(K key, V value) | 普通 | 向集合中加入元素 |
| 11 | public void putAll(Map<? extends K,? extends V> t) | 普通 | 將一個Map集合中的內容加入到另一個Map |
| 12 | public V remove(Object key) | 普通 | 根據key刪除value |
| 13 | public int size() | 普通 | 取出集合的長度 |
| 14 | public Collection<V> values() | 普通 | 取出全部的value |
三、例子
package com.pb.demo2;public class Person {private String name;private int age;public Person() {}public Person(String name, int age) {this.name = name;this.age = age; }public String getName() {return name; } public void setName(String name) {this.name = name; } public int getAge() {return age; } public void setAge(int age) {this.age = age; }} package com.pb.demo2;import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;import com.pb.demo1.Person;public class MapTest {public static void main(String[] args) {/** 1.創建多個Person對象并賦值*/Person p1 = new Person("張三",21);Person p2 = new Person("李四",22);Person p3 = new Person("王五",23);Person p4 = new Person("趙六",24);Person p5 = new Person("錢七",25);//2.創建保存鍵--值對的集合對象Map<String,Person> perMap=new HashMap<String,Person>();//3.使用put將英文名與對象按照鍵-值對的方式在座存儲在HashMap中perMap.put("Denny", p1);perMap.put("Jony", p2);perMap.put("Rose", p3);perMap.put("Kitter", p4);perMap.put("Boby", p5);//4.打印鍵集System.out.println("++++++++打印鍵集+++++++++");System.out.println(perMap.keySet());//5.打印值集System.out.println("=========打印值集=======");System.out.println(perMap.values());//6.打印鍵-值對集合System.out.println("=========打印鍵-值對集合=======");System.out.println(perMap);//7.判斷是否存在"Denny"這個鍵if(perMap.containsKey("Denny")){//8.如果存在,根據鍵獲取相應的值Person p =perMap.get("Denny");System.out.println("姓名: "+p.getName());System.out.println("年齡: "+p.getAge());}System.out.println("=======遍歷HashMap=======");//遍歷HashMap//首先遍歷key集合,keySet方法返回的是Set集合Set<String> keySet=perMap.keySet();Iterator<String> iterator=keySet.iterator();while(iterator.hasNext()){String key=iterator.next();System.out.print("英文名:"+key);//根據key值取出值Person p =perMap.get(key);System.out.print("\t姓名: "+p.getName());System.out.println("\t年齡: "+p.getAge());}}}?
轉載于:https://www.cnblogs.com/liunanjava/p/4300094.html
總結
以上是生活随笔為你收集整理的Java从零开始学二十三(集合Map接口)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zoj 2760 How Many Sh
- 下一篇: 软件工程——理论、方法与实践 第