HashMap
雙列集合:
-------------| Map 如果是實現了Map接口的集合類,具備的特點: 存儲的數據都是以鍵值對的形式存在的,鍵不可重複,值可以重複。
----------------| HashMap 底層也是基於哈希表實現 的。哈希表的作用是用來保證鍵的唯一性的。
HashMap的存儲原理:
往HashMap添加元素的時候,首先會調用鍵的hashCode方法得到元素 的哈希碼值,然後經過運算就可以算出該
元素在哈希表中的存儲位置。
情況1: 如果算出的位置目前沒有任何元素存儲,那麼該元素可以直接添加到哈希表中。
情況2:如果算出的位置目前已經存在其他的元素,那麼還會調用該元素的equals方法與這個位置上的元素進行比較,如果equals方法返回的是false,那麼該元素允許被存儲,如果equals方法返回的是true,那麼該元素被視為
重複元素,不允存儲。
*/
publicclass HashMap01 {
publicstaticvoid main(String[] args) {
HashMap<Person01, String> map = new HashMap<Person01, String>();
map.put(new Person01(110,"狗娃"), "001");
map.put(new Person01(220,"狗剩"), "002");
map.put(new Person01(330,"鐵蛋"), "003");
map.put(new Person01(110,"狗娃"), "007"); //如果出現了相同鍵,那麼後添加的數據的值會取代之前 的值。
System.out.println("集合的元素:"+ map);
}
}
class Person01{
String name;
intid;
public Person01(int id,String name) {
super();
this.id= id;
this.name=name;
}
@Override
public String toString() {
return"[編號:"+this.id+" " +"名字:"+this.name+"]";
}
@Override
publicint hashCode() {
returnthis.id;
}
@Override
publicboolean equals(Object obj) {
Person01 p = (Person01)obj;
returnthis.id== p.id;
}
}
TreeMap TreeMap也是基於紅黑樹(二叉樹)數據結構實現 的, 特點:會對元素的鍵進行排序存儲
*TreeMap 要注意的事項:
1. 往TreeMap添加元素的時候,如果元素的鍵具備自然順序,那麼就會按照鍵的自然順序特性進行排序存儲。
2. 往TreeMap添加元素的時候,如果元素的鍵不具備自然順序特性, 那麼鍵所屬的類必須要實現Comparable接口,把鍵的比較規則定義在CompareTo方法上。
3. 往TreeMap添加元素的時候,如果元素的鍵不具備自然順序特性,而且鍵所屬的類也沒有實現Comparable接口,那麼就必須在創建TreeMap對象的時候傳入比較器。
publicclass ThreeMap01 {
publicstaticvoid main(String[] args) {
/*TreeMap<Student,String> tree = new TreeMap<Student,String>();
tree.put(new Student("葉輝",23), "001");
tree.put(new Student("八戒",24), "002");
tree.put(new Student("信我",27), "003");
tree.put(new Student("王",27), "004");*/
//自定義一個比較器
MyComparator my = new MyComparator();
TreeMap<Student,String> tree = new TreeMap<Student,String>(my);
tree.put(new Student("葉輝",23), "001");
tree.put(new Student("八戒",24), "002");
tree.put(new Student("信我",27), "003");
tree.put(new Student("王",27), "004");
System.out.println(tree);
}
}
class MyComparator implements Comparator<Student>{
@Override
publicint compare(Student o1, Student o2) {
return o1.age-o2.age;
}
}
class Student /*implements Comparable<Student>*/{
intage;
String name;
public Student(String name,int age) {
this.age=age;
this.name=name;
}
/*@Override
public int compareTo(Student o) {
return this.age - o.age;
}*/
@Override
public String toString() {
return"[年齡:"+this.age+" "+ "姓名:"+this.name;
}
}