map hashmap的使用
package map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Map的实现类HashMap使用
*/
public class MapTest {
/**
*
*/
public static void main(String[] args) {
System.out.println("MapGame start...");
BasicUseOfHashMap();
System.out.println("MapGame end...");
}
/**
* HashMap的使用
*/
private static void BasicUseOfHashMap() {
Map<String, String> hashmap = new HashMap<>();
hashmap.put("name", "eric");
hashmap.put("sex", "男");
String value = hashmap.get("sex");
System.out.println(value);
/**
* 增强for循环遍历之使用entrySet循环遍历
*/
System.out.println("\r\n" + "使用entrySet循环遍历");
for (Map.Entry<String, String> entry : hashmap.entrySet()) {
String key1 = entry.getKey();
String value1 = entry.getValue();
System.out.println(key1 + ":" + value1);
}
/**
* 增强for循环遍历之使用keySet循环遍历
*/
System.out.println("\r\n" + "使用keySet循环遍历");
for (String key2 : hashmap.keySet()) {
System.out.println(key2 + ":" + hashmap.get(key2));
}
/**
* 迭代器循环遍历之使用keySet()遍历
*/
System.out.println("\r\n" + "迭代器循环遍历之使用keySet()遍历");
Iterator<String> iterator = hashmap.keySet().iterator();
while (iterator.hasNext()) {
String key3 = iterator.next();
System.out.println(key3 + ":" + hashmap.get(key3));
}
/**
* 迭代器循环遍历之使用entrySet()遍历
*/
System.out.println("\r\n" + "迭代器循环遍历之使用keySet()遍历");
Iterator<Map.Entry<String, String>> iterator1 = hashmap.entrySet().iterator();
while (iterator1.hasNext()) {
Map.Entry<String, String> map = iterator1.next();
String key4 = map.getKey();
String value4 = map.getValue();
System.out.println(key4 + ":" + value4);
}
}
}
java中为什么要使用Iterator?
Iterator模式是用于遍历集合类的标准访问方法。它可以把访问逻辑从不同类型的集合类中抽象出来,从而避免向客户端暴露集合的内部结构。
We only live once, and time just goes by.

浙公网安备 33010602011771号