传统的for循环遍历方式是
//对于数组而言
int[] arr=new int[10];
for(int i=0;i<arr.length;i++){
System.out.print(i);
}
//对于集合要使用迭代器
List<String> list=new ArrayList<>();
for(Iterator<String> i=list.iterator();i.hasNext();){
person=i.next();
System.out.println(person);
}
现在有了for循环的增强形式,可以用很简单的办法迭代
//对于数组
for(int i:arr){
int j=i;
}
//对于集合
for(Person p:list){
String name=p.name;
}
这样特别方便。对于Map的迭代方式
//Map原本使用Entry的方式进行迭代
HashMap<String, Integer> prices = new HashMap<>();
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
for(Entry<String,Integer> e:prices.entrySet()){
System.out.println(e.getKey()+e.getValue());
}
//现在可以直接用keySet
for(String key:prices.keySet()){
System.out.println(prices.get(key));
}
还可以用Lambda表达式
prices.forEach((key,value) -> {
System.out.println(key+" "+value);
});
话说本站的代码编辑器实在太难用了,格式都不带整一下的,这么多年了是怎么活下来的。
使用增强型for循环删除元素的问题
for(String key:prices.keySet()){
prices.remove(key);
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
因为删除元素后迭代器记录的个数不变,但是实际上集合的个数已经减少了
所以删除的话还是要使用Iterator
List<String> list=new ArrayList<>();
list.add("gey");
list.add("p");
list.add("000");
list.add("888");
Iterator<String> it=list.iterator();
while(it.hasNext()){
String s=it.next();
it.remove();
}
//一定要用it.next()获取元素之后再删除,否则会出问题
//map的删除方法
HashMap<String, Integer> prices = new HashMap<>();
// 往 HashMap 中插入映射项
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
Iterator<Entry<String,Integer>> it=prices.entrySet().iterator();
while(it.hasNext()){
Entry<String,Integer> e=it.next();
it.remove();
}
不得不吐槽这格式实在太难用了,怎么没人改进?