16(03)總結增強for迴圈,靜態匯入,可變引數
阿新 • • 發佈:2022-05-04
(1)是for迴圈的一種
(2)格式:
for(元素的資料型別 變數名 : 陣列或者Collection集合的物件) {
使用該變數即可,該變數其實就是陣列或者集合中的元素。
}
(3)好處:
簡化了陣列和集合的遍歷
(4)弊端
增強for迴圈的目標不能為null。建議在使用前,先判斷是否為null。
package cn.itcast_01; import java.util.ArrayList; import java.util.List; /* * JDK5的新特性:自動拆裝箱,泛型,增強for,靜態匯入,可變引數,列舉 * * 增強for:是for迴圈的一種。 * * 格式: * for(元素資料型別 變數名: 陣列名或者Collection集合) { * 使用變數名即可,該變數就是陣列或者集合中的元素 * } * * 好處:簡化了陣列和集合的遍歷。 * * 弊端: 增強for的目標不能為null。 * 如何解決呢?對增強for的目標先進行不為null的判斷,然後在使用。 */ public class ForDemo { public static void main(String[] args) { // 定義一個int陣列 int[] arr = { 1, 2, 3, 4, 5 }; for (int x = 0; x < arr.length; x++) { System.out.println(arr[x]); } System.out.println("---------------"); // 增強for for (int x : arr) { System.out.println(x); } System.out.println("---------------"); // 定義一個字串陣列 String[] strArray = { "林青霞", "風清揚", "東方不敗", "劉意" }; // 增強for for (String s : strArray) { System.out.println(s); } System.out.println("---------------"); // 定義一個集合 ArrayList<String> array = new ArrayList<String>(); array.add("hello"); array.add("world"); array.add("java"); // 增強for for (String s : array) { System.out.println(s); } System.out.println("---------------"); List<String> list = null; // NullPointerException // 這個s是我們從list裡面獲取出來的,在獲取前,它肯定還好做一個判斷 // 說白了,這就是迭代器的功能 if (list != null) { for (String s : list) { System.out.println(s); } } // 增強for其實是用來替代迭代器的 //ConcurrentModificationException // for (String s : array) { // if ("world".equals(s)) { // array.add("javaee"); // } // } // System.out.println("array:" + array); } }
案例:
A:ArrayList儲存字串並遍歷。要求加入泛型,並用增強for遍歷。
package cn.itcast_01; import java.util.ArrayList; import java.util.Iterator; /* * ArrayList儲存字串並遍歷。要求加入泛型,並用增強for遍歷。 * A:迭代器 * B:普通for * C:增強for */ public class ArrayListDemo { public static void main(String[] args) { // 建立集合物件 ArrayList<String> array = new ArrayList<String>(); // 建立並新增元素 array.add("hello"); array.add("world"); array.add("java"); // 遍歷集合 // 迭代器 Iterator<String> it = array.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } System.out.println("------------------"); // 普通for for (int x = 0; x < array.size(); x++) { String s = array.get(x); System.out.println(s); } System.out.println("------------------"); // 增強for for (String s : array) { System.out.println(s); } } }
B:需求:ArrayList儲存自定義物件並遍歷。要求加入泛型,並用增強for遍歷。
package cn.itcast_01;(1) public class Student { // 成員變數 private String name; private int age; // 構造方法 public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } // 成員方法 // getXxx()/setXxx() 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; } } package cn.itcast_01;(2) import java.util.ArrayList; import java.util.Iterator; /* * 需求:ArrayList儲存自定義物件並遍歷。要求加入泛型,並用增強for遍歷。 * A:迭代器 * B:普通for * C:增強for * * LinkedList,Vector,Colleciton,List等儲存我還講嗎?不講解了,但是要求你們練習。 * * 增強for是用來替迭代器。 */ public class ArrayListDemo2 { public static void main(String[] args) { // 建立集合物件 ArrayList<Student> array = new ArrayList<Student>(); // 建立學生物件 Student s1 = new Student("林青霞", 27); Student s2 = new Student("貂蟬", 22); Student s3 = new Student("楊玉環", 24); Student s4 = new Student("西施", 21); Student s5 = new Student("王昭君", 23); // 把學生物件新增到集合中 array.add(s1); array.add(s2); array.add(s3); array.add(s4); array.add(s5); // 迭代器 Iterator<Student> it = array.iterator(); while (it.hasNext()) { Student s = it.next(); System.out.println(s.getName() + "---" + s.getAge()); } System.out.println("---------------"); // 普通for for (int x = 0; x < array.size(); x++) { Student s = array.get(x); System.out.println(s.getName() + "---" + s.getAge()); } System.out.println("---------------"); // 增強for for (Student s : array) { System.out.println(s.getName() + "---" + s.getAge()); } } }
4:靜態匯入(瞭解)
(1)可以匯入到方法級別的匯入
(2)格式:
import static 包名....類名.方法名;
(3)注意事項:
A:方法必須是靜態的
B:如果多個類下有同名的方法,就不好區分了,還得加上字首。
所以一般我們並不使用靜態匯入,但是一定要能夠看懂。
package cn.itcast_02;
/*
* 靜態匯入:
* 格式:import static 包名….類名.方法名;
* 可以直接匯入到方法的級別
*
* 靜態匯入的注意事項:
* A:方法必須是靜態的
* B:如果有多個同名的靜態方法,容易不知道使用誰?這個時候要使用,必須加字首。由此可見,意義不大,所以一般不用,但是要能看懂。
*/
import static java.lang.Math.abs;
import static java.lang.Math.pow;
import static java.lang.Math.max;
//錯誤
//import static java.util.ArrayList.add;
public class StaticImportDemo {
public static void main(String[] args) {
// System.out.println(java.lang.Math.abs(-100));
// System.out.println(java.lang.Math.pow(2, 3));
// System.out.println(java.lang.Math.max(20, 30));
// 太複雜,我們就引入到import
// System.out.println(Math.abs(-100));
// System.out.println(Math.pow(2, 3));
// System.out.println(Math.max(20, 30));
// 太複雜,有更簡單
// System.out.println(abs(-100));
System.out.println(java.lang.Math.abs(-100));
System.out.println(pow(2, 3));
System.out.println(max(20, 30));
}
public static void abs(String s){
System.out.println(s);
}
}
5:可變引數(掌握)
(1)如果我們在寫方法的時候,引數個數不明確,就應該定義可變引數。(本質是陣列)
(2)格式:
修飾符 返回值型別 方法名(資料型別... 變數) {}
注意:
A:該變數其實是一個數組名
B:如果一個方法有多個引數,並且有可變引數,可變引數必須在最後
package cn.itcast_03;
/*
* 可變引數:定義方法的時候不知道該定義多少個引數
* 格式:
* 修飾符 返回值型別 方法名(資料型別… 變數名){
*
* }
*
* 注意:
* 這裡的變數其實是一個數組
* 如果一個方法有可變引數,並且有多個引數,那麼,可變引數肯定是最後一個
*/
public class ArgsDemo {
public static void main(String[] args) {
// 2個數據求和
int a = 10;
int b = 20;
int result = sum(a, b);
System.out.println("result:" + result);
// 3個數據的求和
int c = 30;
result = sum(a, b, c);
System.out.println("result:" + result);
// 4個數據的求和
int d = 30;
result = sum(a, b, c, d);
System.out.println("result:" + result);
// 需求:我要寫一個求和的功能,到底是幾個資料求和呢,我不太清楚,但是我知道在呼叫的時候我肯定就知道了
// 為了解決這個問題,Java就提供了一個東西:可變引數
result = sum(a, b, c, d, 40);
System.out.println("result:" + result);
result = sum(a, b, c, d, 40, 50);
System.out.println("result:" + result);
}
public static int sum(int... a) {
// System.out.println(a);
//return 0;
int s = 0;
for(int x : a){
s +=x;
}
return s;
}
// public static int sum(int a, int b, int c, int d) {
// return a + b + c + d;
// }
//
// public static int sum(int a, int b, int c) {
// return a + b + c;
// }
//
// public static int sum(int a, int b) {
// return a + b;
// }
}
(3)Arrays工具類的一個方法
asList()把陣列轉成集合。
注意:這個集合的長度不能改變。
package cn.itcast_03;
import java.util.Arrays;
import java.util.List;
/*
* public static <T> List<T> asList(T... a):把陣列轉成集合
*
* 注意事項:
* 雖然可以把陣列轉成集合,但是集合的長度不能改變。
*/
public class ArraysDemo {
public static void main(String[] args) {
// 定義一個數組
// String[] strArray = { "hello", "world", "java" };
// List<String> list = Arrays.asList(strArray);
List<String> list = Arrays.asList("hello", "world", "java");
// UnsupportedOperationException
// list.add("javaee");
// UnsupportedOperationException
// list.remove(1);
list.set(1, "javaee");
for (String s : list) {
System.out.println(s);
}
}
}
6:練習(掌握)
A:集合的巢狀遍歷
package cn.itcast_01;(1)
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
package cn.itcast_01;(2)
import java.util.ArrayList;
/*
* 集合的巢狀遍歷
* 需求:
* 我們班有學生,每一個學生是不是一個物件。所以我們可以使用一個集合表示我們班級的學生。ArrayList<Student>
* 但是呢,我們旁邊是不是還有班級,每個班級是不是也是一個ArrayList<Student>。
* 而我現在有多個ArrayList<Student>。也要用集合儲存,怎麼辦呢?
* 就是這個樣子的:ArrayList<ArrayList<Student>>
*/
public class ArrayListDemo {
public static void main(String[] args) {
// 建立大集合
ArrayList<ArrayList<Student>> bigArrayList = new ArrayList<ArrayList<Student>>();
// 建立第一個班級的學生集合
ArrayList<Student> firstArrayList = new ArrayList<Student>();
// 建立學生
Student s1 = new Student("唐僧", 30);
Student s2 = new Student("孫悟空", 29);
Student s3 = new Student("豬八戒", 28);
Student s4 = new Student("沙僧", 27);
Student s5 = new Student("白龍馬", 26);
// 學生進班
firstArrayList.add(s1);
firstArrayList.add(s2);
firstArrayList.add(s3);
firstArrayList.add(s4);
firstArrayList.add(s5);
// 把第一個班級儲存到學生系統中
bigArrayList.add(firstArrayList);
// 建立第二個班級的學生集合
ArrayList<Student> secondArrayList = new ArrayList<Student>();
// 建立學生
Student s11 = new Student("諸葛亮", 30);
Student s22 = new Student("司馬懿", 28);
Student s33 = new Student("周瑜", 26);
// 學生進班
secondArrayList.add(s11);
secondArrayList.add(s22);
secondArrayList.add(s33);
// 把第二個班級儲存到學生系統中
bigArrayList.add(secondArrayList);
// 建立第三個班級的學生集合
ArrayList<Student> thirdArrayList = new ArrayList<Student>();
// 建立學生
Student s111 = new Student("宋江", 40);
Student s222 = new Student("吳用", 35);
Student s333 = new Student("高俅", 30);
Student s444 = new Student("李師師", 22);
// 學生進班
thirdArrayList.add(s111);
thirdArrayList.add(s222);
thirdArrayList.add(s333);
thirdArrayList.add(s444);
// 把第三個班級儲存到學生系統中
bigArrayList.add(thirdArrayList);
// 遍歷集合
for (ArrayList<Student> array : bigArrayList) {
for (Student s : array) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
}
B:產生10個1-20之間的隨機數,要求隨機數不能重複
package cn.itcast_02;
import java.util.ArrayList;
import java.util.Random;
/*
* 獲取10個1-20之間的隨機數,要求不能重複
*
* 用陣列實現,但是陣列的長度是固定的,長度不好確定。
* 所以我們使用集合實現。
*
* 分析:
* A:建立產生隨機數的物件
* B:建立一個儲存隨機數的集合。
* C:定義一個統計變數。從0開始。
* D:判斷統計遍歷是否小於10
* 是:先產生一個隨機數,判斷該隨機數在集合中是否存在。
* 如果不存在:就新增,統計變數++。
* 如果存在:就不搭理它。
* 否:不搭理它
* E:遍歷集合
*/
public class RandomDemo {
public static void main(String[] args) {
// 建立產生隨機數的物件
Random r = new Random();
// 建立一個儲存隨機數的集合。
ArrayList<Integer> array = new ArrayList<Integer>();
// 定義一個統計變數。從0開始。
int count = 0;
// 判斷統計遍歷是否小於10
while (count < 10) {
//先產生一個隨機數
int number = r.nextInt(20) + 1;
//判斷該隨機數在集合中是否存在。
if(!array.contains(number)){
//如果不存在:就新增,統計變數++。
array.add(number);
count++;
}
}
//遍歷集合
for(Integer i : array){
System.out.println(i);
}
}
}
C:鍵盤錄入多個數據,以0結束,並在控制檯輸出最大值
package cn.itcast_03;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/*
* 鍵盤錄入多個數據,以0結束,要求在控制檯輸出這多個數據中的最大值
*
* 分析:
* A:建立鍵盤錄入資料物件
* B:鍵盤錄入多個數據,我們不知道多少個,所以用集合儲存
* C:以0結束,這個簡單,只要鍵盤錄入的資料是0,我就不繼續錄入資料了
* D:把集合轉成陣列
* E:對陣列排序
* F:獲取該陣列中的最大索引的值
*/
public class ArrayListDemo {
public static void main(String[] args) {
// 建立鍵盤錄入資料物件
Scanner sc = new Scanner(System.in);
// 鍵盤錄入多個數據,我們不知道多少個,所以用集合儲存
ArrayList<Integer> array = new ArrayList<Integer>();
// 以0結束,這個簡單,只要鍵盤錄入的資料是0,我就不繼續錄入資料了
while (true) {
System.out.println("請輸入資料:");
int number = sc.nextInt();
if (number != 0) {
array.add(number);
} else {
break;
}
}
// 把集合轉成陣列
// public <T> T[] toArray(T[] a)
Integer[] i = new Integer[array.size()];
// Integer[] ii = array.toArray(i);
array.toArray(i);
// System.out.println(i);
// System.out.println(ii);
// 對陣列排序
// public static void sort(Object[] a)
Arrays.sort(i);
// 獲取該陣列中的最大索引的值
System.out.println("陣列是:" + arrayToString(i) + "最大值是:"
+ i[i.length - 1]);
}
public static String arrayToString(Integer[] i) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int x = 0; x < i.length; x++) {
if (x == i.length - 1) {
sb.append(i[x]);
} else {
sb.append(i[x]).append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
7:要掌握的程式碼
集合儲存元素,加入泛型,並可以使用增強for遍歷。