java集合,java集合類詳解
---恢複內容開始---
Map集合:HashMap、HashTable、LinkedHashMap
HashTable實現原理:基於雜湊表實現,用作鍵的對象必須實現hashCode()和equals()方法,因為在Map中鍵是唯一的。注意HashTable中鍵和值都不允許為null。
線程同步,安全。
HashMap的實現原理:與HashTable原理一樣,但是在HashMap中鍵允許為null,值也允許為null。jdk1.2中出現步jdk1.0中出現。線程不同步,不安全。
package collection;import java.util.Hashtable;import java.util.*;import java.util.Map.Entry;import java.util.Set;public class MyMap1 { public static void main(String[] args) { Map<Person,Contact> m1 = new Hashtable<Person,Contact>(); Person p1 = new Person(13,"zhangsan"); Person p2 = new Person(14,"lisi"); Person p3 = new Person(13,"zhangsan"); Person p4 = new Person(13,"zhangsan"); Contact c1 = new Contact(378989,"湖南"); Contact c2 = new Contact(378989,"北京"); Contact c3 = new Contact(378989,"北京"); Contact c4 = new Contact(378989,"北京"); m1.put(p1, c1); m1.put(p2, c2); m1.put(p3, c3); m1.put(p4, c4); for( Entry<Person, Contact> entry:m1.entrySet()){ System.out.println(entry.getKey()+"-"+entry.getValue()); }// System.out.println(m1); }}class Person { int id ; String name; public Person(int id, String name) { //super(); this.id = id; this.name = name; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } }class Contact{ int telephont; String address; public Contact(int telephont, String address) { //super(); this.telephont = telephont; this.address = address; } @Override public String toString() { return "Contact [telephont=" + telephont + ", address=" + address + "]"; } }View Code
---恢複內容開始---Map集合:HashMap、HashTable、LinkedHashMap HashTable實現原理:基於雜湊表實現,用作鍵的對象必須實現hashCode()和equals()方法,因為在Map中鍵是唯一的。注意HashTable中鍵和值都不允許為null。 線程同步,安全。 HashMap的實現原理:與HashTable原理一樣,但是在HashMap中鍵允許為null,值也允許為null。jdk1.2中出現步jdk1.0中出現。線程不同步,不安全。 View Code
總結:雖然Person沒有實現hashCode和equals方法,但是Object類中有這兩個方法,m1在調用put方法時會調用Object裡面的這兩個方法,實現儲存。
首先調用hashCode方法產生一個該對象的雜湊碼值,通過雜湊碼值找到該對象在雜湊表中的位置,如果該位置已經被其他對象佔用了則比較這兩個對象的雜湊碼值。
若這兩個雜湊碼值一樣,那麼調用equals方法比較,若計較結果一樣,則不予儲存,若比較結果不一樣,則在此位置順延一下儲存該對象。
若這兩個雜湊碼值不一樣則在該位置順延一下儲存該對象。