1. 程式人生 > >Java 集合——Map集合

Java 集合——Map集合

是存放一對值的最大介面,即介面中的每一個元素都是一對,以key->value鍵值對的形式儲存;

我們這裡講解下Map的常用實現類HashMap;

package com.xuyigang1234.chp06.sec01;

import java.util.HashMap;
import java.util.Iterator;

public class TestHashMap {
    public static void main(String[] args) {
        HashMap<String,Student> hashMap = new HashMap<String,Student>();
        hashMap.put(
"1", new Student("小紅",10)); hashMap.put("2", new Student("小白",10)); hashMap.put("3", new Student("小名",10)); // foreach 遍歷 for(String i:hashMap.keySet()) { //key 值集合 Student stu=hashMap.get(i); System.out.println("key值="+i+",姓名:"+stu.getName()+",年齡="+stu.getAge()); }
// 迭代器遍歷 Iterator<String> it=hashMap.keySet().iterator(); // 獲取key的集合,再獲取迭代器 while(it.hasNext()){ String key=it.next(); // 獲取key Student student=hashMap.get(key); // 通過key獲取value System.out.println("key="+key+" value=["+student.getName()+","+student.getAge()+"]"); } } ; }
key值=1,姓名:小紅,年齡=10
key值=2,姓名:小白,年齡=10
key值=3,姓名:小名,年齡=10
key=1 value=[小紅,10]
key=2 value=[小白,10]
key=3 value=[小名,10]