HashMap的用法(两种迭代方法案例)

xiaoxiao2021-02-28  243

package TestMap; import java.util.*; /** * Created by Administrator on 2017/5/5. */ public class Testpet { public static void main(String[] args) { Map pets = new HashMap(); pets.put("旺旺", "企鹅"); pets.put("欧欧", "雪瑞娜"); pets.put("汤姆", "猫"); pets.put("杰瑞", "老鼠"); Set keys = pets.keySet(); /* 迭代输出方法一 Iterator it = keys.iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) pets.get(key); System.out.println(key + "\t\t" + value); }*/ //方法二 for (Object key:keys) { String value = (String) pets.get(key); System.out.println(key+" "+value); } }

}

运行结果:

杰瑞    老鼠 旺旺    企鹅 欧欧    雪瑞娜 汤姆    猫

转载请注明原文地址: https://www.6miu.com/read-34056.html

最新回复(0)