zoukankan      html  css  js  c++  java
  • Java数组定义学习的一些随笔

    //一维数组的定义
    		int[] arr1 = new int[3];//arr1 = {1,2,3}; 错误
    		int[] arr2 = new int[]{1,2,3};//int[] arr2 = new int[3]{1,2,3}; 错误
    		int arr3[] = {4,5,6};
    		//二维数组的定义
    		//二维数组中一维数组长度一致的数组
    		int[][] arr4 = new int[2][3];
    		
    		//二维数组中一维数组长度不一致的数组  2个一维数组 一个长度2 一个长度3
    		int[][] arr5 = new int[2][];
    		arr5[0] = new int[2];
    		arr5[1] = new int[3];
    		//遍历
    		for(int[] i : arr5){
    			for(int k : i){
    				System.out.println(k);
    				if(k == i.length - 3)
    					System.out.print("good");//这里边有个有趣的问题
    			}
    		}
    

      ps

    1. 数组声明时,int[] arr 与 int arr[] 都是可以的
      int[] arr2 = new int[]{1,2,3};
      int arr3[] = {4,5,6};
      

        

    2. 初始化时,才能使用大括号{, , ,},声明完arr1 ,如果赋值是这样 arr1 = {1,2,3};是错误的,应该单独赋值或使用循环,arr1[0] = 1
    3. 初始化时,使用大括号时不应该数组加长度 ,int[] arr2 = new int[3]{1,2,3};这个语句是错误的
      int[] arr2 = new int[]{1,2,3};
      int arr3[] = {4,5,6};
      

        

    4. 再使用foreach遍历的时候,以上输出代码的结果是
      0
      0
      0
      good0
      good0
      good
      

        二维数组arr5是没有被初始化的,所以默认值都是0,为什么我代码中写的是 k == i.length - 3 会输出后三个good 呢,k的默认值可都是0,所以原因就是,这个i的长度会变化,长度变化的原因其实就是这是两个int[] i 数组,第一个数组长度是2 第二个长度是3

      //如果我把代码修改为
       k == i.length - 2
      
      //则输出结果就为 
      
      0
      good0
      good0
      0
      0
      
      //原因在于 当遇到第一个数组时,长度是2,所以会执行语句,当遇到第二个一维数组时,因为长度是3,所以
      //i.length - 1 为1,所以不等于k(默认为0)
      

        综上所述,意思就是说,第二个foreach其实是连续遍历其中的所有一维数组。

    5. 还有在二维数组中,直接使用arr5.length 返回的是二维数组中一维数组个数,arr5[0].length 返回的是其中这个一维数组的长度
  • 相关阅读:
    Application
    Intent
    C#Winform实现自动更新
    Activity的四种启动模式
    小白学Python——用 百度翻译API 实现 翻译功能
    小白学Python——用 百度AI 实现 OCR 文字识别
    小白学Python——Matplotlib 学习(3) 函数图形
    小白学Python——Matplotlib 学习(2):pyplot 画图
    小白学Python——Matplotlib 学习(1)
    小白学Python(20)—— Turtle 海龟绘图
  • 原文地址:https://www.cnblogs.com/whytohow/p/4863183.html
Copyright © 2011-2022 走看看