HashTable 是非常常用的一种容器,其通过key-value键值对保存数据的数据结构。
一. 主要特点:
1. 是线程安全的。 其内部方法均已加同步关键字。
2. 它的key和value都不可以是空的。
3. 里面存取的数据是无序的。 这点从下面demo1中可以看出来。
4. 其数据结构为哈希表。
线程安全说明:
public synchronized V put(K var1, V var2) {...}
二 遍历方式
主要有4种方式,两种枚举,两种迭代器。枚举主要在老项目中使用,正逐渐被迭代器替代。详情请参考Demo2.
三 Demo1:
public class myClass { static Hashtable tempTalbe = new Hashtable(); public static void main(String[] args) { addDateInThreadOne(); addDateInThreadTwo(); } public static void addDateInThreadOne(){ new Thread(){ @Override public void run() { try{ Thread.sleep(1000); } catch (InterruptedException E){ E.printStackTrace(); } tempTalbe.put("one", "Father"); tempTalbe.put("two", "Mather"); System.out.println("TempTable ="+tempTalbe); } }.start(); } public static void addDateInThreadTwo(){ new Thread(){ @Override public void run() { tempTalbe.put("three", "Brother"); tempTalbe.put("four", "Syster"); System.out.println("TempTable ="+tempTalbe); } }.start(); } }
输出:
TempTable ={three=Brother, four=Syster}
TempTable ={two=Mather, one=Father, three=Brother, four=Syster}
Process finished with exit code 0
Demo1: 展示了存储数据的无序行,和一定程度上说明了HashTable的线程安全。|
Demo2:
public class myClass { static Hashtable tempTalbe = new Hashtable(); public static void main(String[] args) { tempTalbe.put("1", "son1"); tempTalbe.put("2", "son2"); //遍历方法1 //key-value key 值迭代器(推荐) System.out.println("遍历方法1"); Iterator<String> firstIterator = tempTalbe.keySet().iterator(); while (firstIterator.hasNext()) { String str = firstIterator.next(); System.out.println("str ="+str); String value = tempTalbe.get(str).toString(); System.out.println("value ="+value); } //遍历方法2 //key-value迭代器(推荐) System.out.println("遍历方法2"); Iterator<Map.Entry> secondIterator = tempTalbe.entrySet().iterator(); while (secondIterator.hasNext()){ Map.Entry<String, String> temp = secondIterator.next(); System.out.println("temp key"+temp.getKey() +"; value ="+temp.getValue()); } //遍历方法3 //获得key-value中的keys的枚举(正被迭代器取代) System.out.println("遍历方法3"); Enumeration<String> tempkeys= tempTalbe.keys(); while (tempkeys.hasMoreElements()){ String tempkey = tempkeys.nextElement().toString(); System.out.println("tempkey ="+tempkey +"; vaule ="+tempTalbe.get(tempkey)); } //遍历方法4 //获得key-value中的values 枚举(正被迭代器取代) System.out.println("遍历方法4"); Enumeration<String> values = tempTalbe.elements(); while (values.hasMoreElements()){ String value = values.nextElement(); System.out.println("fiveValue ="+value); } } }输出:
遍历方法1
str =2
value =son2
str =1
value =son1
遍历方法2
temp key2; value =son2
temp key1; value =son1
遍历方法3
tempkey =2; vaule =son2
tempkey =1; vaule =son1
遍历方法4
fiveValue =son2
fiveValue =son1
Process finished with exit code 0