hashtable遍历java_HashTable的五种遍历方式

package com.xing.lab.util;

import java.util.Enumeration;

import java.util.Hashtable;

import java.util.Iterator;

import java.util.Map;

import java.util.Map.Entry;

public class TraverseHashTable {

public static void main(String[] args) {

Hashtable hashtable = new Hashtable();

hashtable.put("1", "aa");

hashtable.put("2", "bb");

hashtable.put("3", "cc");

//第一种hashtable遍历方式

System.out.println("第一种遍历方式");

for (Iterator iterator = hashtable.keySet().iterator();iterator.hasNext();) {

String key = iterator.next();

System.out.println("key-----" + key);

System.out.println("value--------" + hashtable.get(key));

}

//第二种hashtable遍历方式

System.out.println("第二种遍历方式");

for (Iterator> iterator = hashtable.entrySet().iterator();

iterator.hasNext();) {

Entry entry = iterator.next();

System.out.println("key---------" + entry.getKey());

System.out.println("value------------" + entry.getValue());

}

//第三种hashtable遍历方式

System.out.println("第三种遍历方式");

for (Map.Entry entry : hashtable.entrySet()) {

System.out.println("key---------" + entry.getKey());

System.out.println("value--------" + entry.getValue());

}

//第四种遍历方式

System.out.println("第四种遍历方式");

Enumeration e = hashtable.keys();

while (e.hasMoreElements()) {

String key = e.nextElement();

System.out.println("key-----" + key);

System.out.println("value-------" + hashtable.get(key));

}

//第五中遍历方式(获取所有的值)

System.out.println("第五种遍历方式");

Enumeration e2 = hashtable.elements();

while (e2.hasMoreElements()) {

String string = (String) e2.nextElement();

System.out.println(string);

}

}

}


版权声明:本文为weixin_32459553原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。