Map:存入索引值對,同時要保證鍵的唯一性.
|--HashMap: 採用雜湊表資料結構.判斷重複元素需要覆蓋hashCode、equals方法,HashSet由HashMap得來.
線程不安全,可以存放null鍵、null值.
|--HashTable:資料結構同樣是雜湊表,安全執行緒,不可以存放null鍵、null值,效率低,被HashMap取代.
|--TreeMap: 採用二叉樹資料結構.可以對TreeMap集合中的鍵進行排序.
※注意:1、區分HashMap、HashTable的區別:執行緒安全性不同,是否可以存放null值,效率.
2、
Map集合取出元素的原理:
先將Map轉成Set集合,然後對Set集合進行迭代.
keySet:將所有的鍵取出放在Set集合中,在根據Set集合得到的key值取出value值.
entrySet:將索引值的關係取出存入Set集合,監製關係有自己的類型,為Map介面中定
義的靜態介面Map.Entry.可以通過getKey(),getValue()方法取值,
什麼時候使用Map集合?
————當出現了對象之間存在映射關係時,就需要使用Map集合.
import java.util.*;
class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap<Student, String> hm = new TreeMap<Student, String>(
new Comparator<Student>()
{
public int compare(Student st1, Student st2)
{
if (st1.getAge() > st2.getAge())
return 1;
else if (st1.getAge() == st2.getAge())
return st1.getName().compareTo(st2.getName());
return -1;
}
});
hm.put(new Student("張三", 20), "北京");
hm.put(new Student("李四", 21), "西安");
hm.put(new Student("王五", 15), "重慶");
hm.put(new Student("趙六", 26), "成都");
hm.put(new Student("孫悅", 25), null); //HashMap可以存null值,而HashTable不可以,因此,不能用get方法返回null來判斷索引值是否存在,而應該用containsKey方法判斷.
//注意:put方法有傳回值,返回的是索引值對應關係的值,集合中原來對索引值沒有指定關係,返回null,有則返回原來的值.
String a = hm.put(new Student("小七", 12), "綿陽"); //原來集合中沒有對索引值(new Student("小七", 12))指定關係,返回為null
//hm.put(new Student("小七", 12), "綿陽"); //未覆蓋hashCode方法和equals方法時,能夠存入相同的元素.
String b = hm.put(new Student("小七", 12), "太原"); //原來對該索引值(new Student("小七", 12))指定了對應關係,返回原來已經指定的值.而這裡的太原覆蓋了原來的綿陽.
System.out.println(a + ".." + b);
Set <Map.Entry<Student, String>> s = hm.entrySet();
for (Iterator<Map.Entry<Student, String>> it = s.iterator(); it.hasNext(); )
{
Map.Entry<Student, String> me = it.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu.getName() + ".." + stu.getAge() + ".." + addr);
}
}
}
class Student
{
private String name;
private int age;
Student(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int hashCode() //注意,判斷HashSet、HashMap集合的唯一性,覆蓋hashCode和equals方法,而TreeMap、TreeMap排序實現comparable或comparator介面.
{
return name.hashCode() + age*29;
}
public boolean equals(Object obj)
{
if (!(obj instanceof Student))
return false;
Student student = (Student)obj;
return this.name.equals(student.name) && this.age == student.age;
}
public String toString()
{
return name + ".." + age;
}
}