【127天】尚学堂高琪Java300集视频精华笔记(60-61)

第60集:多维数组、基本语法、内存分析

二维数组定义及初始化


动态初始化

package com.test060_061;

public class Test1 {
    public static void main(String[] args){
    //静态初始化
    int[][] a = {{1,2,3},{3,4,5},{2,3}};    
}

静态初始化

package com.test060_061;

public class Test1 {
    public static void main(String[] args){    
    //动态初始化
    int[][] b = new int[3][];
    b[0] = new int[]{1,2};
    b[1] = new int[]{2,3,4};
    b[2] = new int[]{3,4,5,6};
//    b[3] = new int[]{3,3,2}; //超范围,错误
    System.out.println(b[2][2]);
    }
}

其它初始化注意事项

package com.test060_061;

public class Test1 {
    public static void main(String[] args){
    
    //int[][] c = new int[][3];//错误
    
    int[][] d = new int[3][1];
    
    }
}

第61集

本集讲了一个矩阵运算的例子,高老师有个地方写的不太清楚了,容易误导人,我在下面改良了一下

package com.test061;

public class Test61 {
    public int[][] add (int[][] a,int[][] b){
        int [][] c = new int[a.length][]; 
        for(int i = 0;i<a.length;i++){
            c[i] = new int[a[i].length];
        }
            
            
        for(int i = 0; i < a.length;i++){
            for(int j = 0;j < a[i].length;j++){//视频中是a.length但这样不好,改成a[i].length适应的范围更广,比如我这个不规则的二维数组。
                c[i][j] = a[i][j] + b[i][j];
            }
        }
        return c ;
    }    


    public static void main(String[] args){
        Test61 test = new Test61();
        int[][] a = new int[][]{{1,1},{1,1,1},{1,1}};
        int[][] b = new int[3][];
        b[0] = new int[]{1,1};
        b[1] = new int[]{1,1,1};
        b[2] = new int[]{1,1};
        
        int[][] d = test.add(a, b);
        
        for(int i = 0;i<d.length;i++){
            for(int j = 0;j<d[i].length;j++){
                System.out.print(d[i][j]+"\t");
            }
            System.out.println();
        }
        
    }

}

评论

暂无评论