java中map集合的原理與應用

Map集合:該集合存儲鍵值對。一對一對往裏存。而且要保證鍵的唯一性。
Map有三種類型:
1.Hashtable:底層是哈希表數據結構,不可以存入null鍵null值。該集合是線程同步的。jdk1.0.效率低。

2.HashMap:底層是哈希表數據結構,允許使用 null 值和 null 鍵,該集合是不同步的。將hashtable替代,jdk1.2.效率高。

3.TreeMap:底層是二叉樹數據結構。線程不同步。可以用於給map集合中的鍵進行排序。

map和Set很像,Set底層就是使用了Map集合。
map集合的一些方法:

1,添加 
    put(K key, V value) 
    putAll(Map<? extends K,? extends V> m) 

2,刪除。
clear()
remove(Object key)
3,判斷。
containsValue(Object value)
containsKey(Object key)
isEmpty()
4,獲取。
get(Object key)
size()
values()
entrySet()
keySet()

map集合的兩種取出方式:
1,Set keySet:將map中所有的鍵存入到Set集合。因爲set具備迭代器。
所有可以迭代方式取出所有的鍵,在根據get方法。獲取每一個鍵對應的值。
Map集合的取出原理:將map集合轉成set集合。在通過迭代器取出。
其結構如圖:
這裏寫圖片描述

    2、Set<Map.Entry<k,v>> entrySet:將map集合中的映射關係存入到了set集合中,而這個關係的數據類型就是:Map.Entry

            Entry其實就是Map中的一個static內部接口。
            爲什麼要定義在內部呢?
            因爲只有有了Map集合,有了鍵值對,纔會有鍵值的映射關係。
            關係屬於Map集合中的一個內部事物。
            而且該事物在直接訪問Map集合中的元素。

結構如圖所示:
這裏寫圖片描述

map的使用方法如代碼所示:

/*
每一個學生都有對應的歸屬地。
學生Student,地址String。
學生屬性:姓名,年齡。
注意:姓名和年齡相同的視爲同一個學生。
保證學生的唯一性。

1,描述學生。

2,定義map容器。將學生作爲鍵,地址作爲值。存入。

3,獲取map集合中的元素。

*/

import java.util.*;
 class Student implements Comparable<Student>
 {
private String name;
private int age;
Student(String name,int age)
{
    this.name = name;
    this.age = age;
}

public int compareTo(Student s)
{
    int num = new Integer(this.age).compareTo(new Integer(s.age));

    if(num==0)
        return this.name.compareTo(s.name);
    return num;
}

public int hashCode()
{
    return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
    if(!(obj instanceof Student))
        throw new ClassCastException("類型不匹配");

    Student s = (Student)obj;

    return this.name.equals(s.name) && this.age==s.age;


}
public String getName()
{
    return name;
}
public int getAge()
{
    return age;
}
public String toString()
{
    return name+":"+age;
}
 }



  class  MapTest
 {
public static void main(String[] args) 
{
    HashMap<Student,String> hm = new HashMap<Student,String>();

    hm.put(new Student("lisi1",21),"beijing");
    hm.put(new Student("lisi1",21),"tianjin");
    hm.put(new Student("lisi2",22),"shanghai");
    hm.put(new Student("lisi3",23),"nanjing");
    hm.put(new Student("lisi4",24),"wuhan");

    //第一種取出方式 keySet

    Set<Student> keySet = hm.keySet();

    Iterator<Student> it = keySet.iterator();

    while(it.hasNext())
    {
        Student stu = it.next();
        String addr = hm.get(stu);
        System.out.println(stu+".."+addr);
    }


    //第二種取出方式 entrySet
    Set<Map.Entry<Student,String>> entrySet = hm.entrySet();

    Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();

    while(iter.hasNext())
    {
        Map.Entry<Student,String> me = iter.next();
        Student stu = me.getKey();
        String addr = me.getValue();
        System.out.println(stu+"........."+addr);
    }
}
 }
發佈了46 篇原創文章 · 獲贊 20 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章