文章目录


Java.集合.增强for循环—foreach

JDK5.0及其以后新特性:增强for循环

   语法:
for(类型 变量:数组名/集合名){
......
}

集合想要使用增强for循环这种语法,集合需要使用泛型;
不使用泛型的时候,必须声明为Object类型

import java.util.*;
public class ForeachTest01 {
/**
* @param args
*/
public static void main(String[]) {
// TODO Auto-generated method stub

//创建一个数组
int[] a = {1,3,5,4,6};

//遍历 for循环
for(int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
System.out.println("==============");

//使用增强for循环 foreach
for(int element:a){
System.out.println(element);
}
System.out.println("==============");

//采用集合
Set<String> str = new HashSet<String>();

//添加元素
str.add("西瓜");
str.add("冬瓜");
str.add("南瓜");
str.add("麻瓜");

//使用增强for循环
for(String name:str){
System.out.println(name);
}
System.out.println("==============");

//集合不使用泛型
List l = new ArrayList();
l.add(1);
l.add(9);
l.add(8);
l.add(5);

//使用增强for循环
for(Object o:l){ //不使用泛型的时候,必须声明为Object类型
System.out.println(o);
}
System.out.println("==============");

//追加字符比较
StringBuffer sb = new StringBuffer();
String[] location = {"东","南","西","北"};

/*
//普通for循环
for(int i = 0; i < location.length; i++){
if(i==location.length-1){
sb.append(location[i]);
}else{
sb.append(location[i]);
sb.append(",");
}
}
System.out.println(sb);
System.out.println("==============");
*/

//使用增强for循环
for(String s:location){
sb.append(s);
sb.append(",");
}
System.out.println(sb);
System.out.println("==============");
//截取最后的分隔符
System.out.println(sb.substring(0, sb.length()-1));
}
}
1
3
5
4
6
==============
1
3
5
4
6
==============
冬瓜
麻瓜
南瓜
西瓜
==============
1
9
8
5
==============
,,西,,
==============
,,西,

返回顶部