高級for 循環創建數組和集合


高級for循環:

格式: for(數據類型 變量名:被遍歷的集合(Collection)或者數組)

   對集合進行遍歷。只能獲取元素,當時不能對集合進行操作。

可變參數:數組參數的簡寫形式,不用每一次都手動的建立數組對象。只要將要操作的元素作為參數傳遞即可。隱式將這些參數封裝成了數組。使用時,可變參數一定要定義在參數列表后邊。

public class Jihe {
    public static void main(String[] args) {
        
         show("haha","bai","", "", "");
             }
              public static void show(String ...arr ){
                  System.out.println(“數組arr的度:”+arr.length);

                 for(int i=0;i<arr.length;i++){
                     System.out.println(“數組下標為”+i+"值:”+arr[i]);
                 }
              }
     }

結果為:

數組arr的度:5
數組下標為0值:haha
數組下標為1值:bai
數組下標為2值:王
數組下標為3值:郇
數組下標為4值:鞏

public class Jihe {
    public static void main(String[] args) {
        
         show("haha", 1, 2, 3, 4);
             }
              public static void show(String s, int ...arr ){
                  System.out.println(arr.length);
                  
                 for(int i=0;i<arr.length;i++){
                     System.out.println("數組下標為"+i+"值:"+arr[i]);
                 }
              }
     }

結果為:

4
數組下標為0值:1
數組下標為1值:2
數組下標為2值:3
數組下標為3值:4

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM