您的位置:首页 > 编程语言 > Java开发

java中for和foreach的区别

2016-07-01 12:41 766 查看
普通for循环

for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
list.remove(i);
}

普通for循环在遍历集合时使用下标来定位集合中的元素,java在jdk1.5中开始支持foreach循环,foreach在一定程度上简化了对集合的遍历,但是foreach不能完全代替for循环

限制场景:
1、使用foreach来遍历集合时,集合必须实现Iterator接口,foreach就是使用Iterator接口来实现对集合的遍历的
2、在用foreach循环遍历一个集合时不能向集合中增加元素,不能从集合中删除元素,否则会抛出ConcurrentModificationException异常。抛出该异常是因为在集合内部有一个modCount变量用于记录集合中元素的个数,当向集合中增加或删除元素时,modCount也会随之变化,在遍历开始时会记录modCount的值,每次遍历元素时都会判断该变量是否发生了变化,如果发生了变化则抛出ConcurrentModificationException异常
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
for(String str:list){
System.out.println(str);
list.add("3");
}
}

3、当使用foreach循环基本类型时变量时不能修改集合中的元素的值,遍历对象时可以修改对象的属性的值,但是不能修改对象的引用
修改基本类型的值(原集合中的值没有变化,因为str是集合中变量的一个副本):
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("0");
list.add("1");
list.add("2");
for(String str:list){
str=str+"0";
System.out.println(str);
}
System.out.println(list);
}
修改对象的值(可以修改,因为f是一个指针):
public class ForE {
private String name;
private int age;

public ForE(String name, int age) {
super();
this.name = name;
this.age = age;
}
public static void main(String[] args) {
List<ForE> list = new ArrayList<ForE>();
list.add(new ForE("apple", 10));
list.add(new ForE("banana", 20));
list.add(new ForE("orange", 30));
for(ForE f:list){
f.setAge(f.getAge()*2);
}
System.out.println(list);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "ForE [name=" + name + ", age=" + age + "]";
}

}<span style="font-family:Helvetica, 'Hiragino Sans GB', 微软雅黑, 'Microsoft YaHei UI', SimSun, SimHei, arial, sans-serif;color:#000000;font-size: 15.238096237182617px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 22.85714340209961px; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; display: inline !important; float: none;"></span>
4、当在遍历时需要根据元素在集合中的index的时候不能使用foreach
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  for foreach java