62,614
社区成员
发帖
与我相关
我的任务
分享
那不叫数组,叫集合
List
Set
Map
List和Set都可以用for each来遍历,如
for (Type t : (List|Set)instance)... ,
或者用iterator来遍历
Iterator<Type> it = (List|Set)instance.iterator();
while (it.hasNext()) ...
Map也可以用for each来遍历,如
for (Map.Entry<KeyType, ValueType> e : Map-instance) {
e.getKey();
e.getValue();
...
}
也可以用Key的集合或Value的集合来遍历,和Set的遍历差不多,如
for (KeyType kt : Map-instance.keySet()) ...
for (ValueType vt : Map-instance.values()) ...
Map<String,Integer> hh = new HashMap<String,Integer>();
hh.put("zhangsan", 123);
hh.put("lis", 312);
hh.put("wangwu", 833);
for(Map.Entry<String, Integer> entry: hh.entrySet()){
System.out.println(entry.getKey() +" : "+entry.getValue());
}
public static void main(String[] args) throws Exception
{
HashMap map = new HashMap();
map.put("A", "北京");
map.put("B","上海");
Set set = map.keySet();//set不能取所以先转换成能取的
ArrayList list = new ArrayList(set);
for(int i=0;i<list.size();i++)
{
System.out.println("key="+list.get(i));
System.out.println("value="+map.get(list.get(i)));
}
}