java中for和foreach的区别

普通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

  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值