Java String之遍历集合或数组新方法——新循环遍历集合

版权声明:转载注明来源。Keep Learning and Coding. https://blog.csdn.net/a771581211/article/details/88384099
package day04;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 新循环遍历集合
 * @author kaixu
 *
 */
public class NewForDemo2 {

	public static void main(String[] args) {
		Collection c = new ArrayList();
		c.add("one");
		c.add("#");
		c.add("two");
		c.add("#");
		c.add("three");
		c.add("#");
		c.add("four");
		System.out.println(c);
		
		/*
		 * 新循环并非新的语法,新循环是编译器认可,而不是虚拟机认可。
		 * 使用新循环遍历集合时,编译器会将它改为迭代器方式遍历。
		 * 所以在使用新循环遍历集合时,不能通过集合的方法增删元素。
		 */
		for(Object o:c){
			//Iterator it = c.iterator()
			//while(it.hasNext()){
			//Object o = it.next();
			//}
			String str = (String)o;
			System.out.println(str);
			if("#".equals(str)){
				c.remove(str);
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/a771581211/article/details/88384099