目录
增强for循环
遍历数组
int[] arr = {10, 50, 30, 90, 25, 30};
//普通for循环
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}//增强for循环 JDK1.5
//for(容器中元素的数据类型 变量名:容器名)
for (int ele : arr) {
System.out.println(ele);
}Integer[] arr2 = {10, 50, 30, 90, 25, 30};
for (Integer ele : arr2) {
System.out.println(ele);
}
遍历集合
ArrayList<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");
list.add("fff");for (int i = 0; i < list.size(); i++) { //普通循环
String s = list.get(i);
System.out.println(s);
}for (String s : list) { //增强for循环
System.out.println(s);
}
遍历对象
ArrayList<Student> list = new ArrayList<>();
list.add(new Student("张三", 23));
list.add(new Student("李四", 24));
list.add(new Student("王五", 25));
list.add(new Student("赵六", 26));for (int i = 0; i < list.size(); i++) { //普通for循环
Student student = list.get(i);
System.out.println(student.getName() + "===" + student.getAge());
}for (Student student : list) { //增强for循环
System.out.println(student.getName() + "===" + student.getAge());
}
注意:快捷键 list.for
为语法糖,实际是迭代器遍历,会报并发修改异常
ArrayList<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");
list.add("fff");
//判断集合中如果有aaa 这个元素我就加一个hello
//使用新式for循环,要注意,在遍历途中不能增删元素
for (String s : list) {
//ConcurrentModificationException
if (s.equals("aaa")) {
//list.add("hello");
list.remove("fff");
}
}/* for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (s.equals("aaa")) {
list.add("hello");
}
}System.out.println(list);*/
可变参数
定义方法的时候不知道该定义多少个参数
可变参数:实际上他是数组 用 a.length 验证
传统add方法
public class MyTest {
public static void main(String[] args) {
int sum1 = add(2, 6);
int sum2 = add(2, 6, 7);
int sum3 = add(2, 6, 7, 8);
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
/* public static int add(int a,int b){
return a+b;
}
public static int add(int a, int b,int c) {
return a + b+c;
}
public static int add(int a, int b, int c,int d) {
return a + b + c+d;
}*/
}
可变参数方法
public static int add(int... a) {
System.out.println(a.length); //数组长度
int sum = 0;
for (int i : a) {
sum += i;
}
return sum;
}