在学习数据结构,遍历栈中元素时,用到了,特意来记个笔记
for循环和foreach循环是可以相互转换的
格式:
声明数组类型:要遍历的数组
例子:
int[] num = {1,2,3,4,5,6};for(int i: num){System.out.print(i);}
弹栈部分代码
//创建栈对象Stack<String> stack = new Stack<>();//测试压栈stack.push("a");stack.push("b");stack.push("c");stack.push("d");for (String item : stack) {System.out.println(item);}
用法:
for(ElementType element: arrayName){};
遍历集合
List<Integer> intList = new ArrayList<Integer>();for (Integer i: intList) {System.out.print(i);}
总结:
相对于for(;;)而言 增强for循环有两个好处:
1.写起来简单,不用再老是判断for循环的边界
2.遍历集合、容器简单
参考链接:
/yrwan95/article/details/81230046
/qq_47610562/article/details/113072417