4.7稀疏数组
public static void main(String[] args) { int[][] array1 = new int[11][11]; array1[1][2] = 1; array1[2][3] = 2; System.out.println("原始数组"); for (int[] ints : array1) { for (int anInt : ints) { System.out.print(anInt + "\t"); } System.out.println(); } int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if (array1[i][j] != 0){ sum++; } } } System.out.println("有效数组个数" + sum); //稀疏矩阵 array2【行数】【列数】【内容】 int array2[][] = new int[sum+1][3]; array2[0][0] = 11; array2[0][1] = 11; array2[0][2] = sum; int count = 0; for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array1[i].length; j++) { if (array1[i][j] != 0){ count++; array2[count][0] = i; array2[count][1] = j; array2[count][2] = array1[i][j]; } } } System.out.println("稀疏数组"); for (int[] ints : array2) { for (int anInt : ints) { System.out.print(anInt + "\t"); } System.out.println(); } int[][] array3 = new int[array2[0][0]][array2[0][1]]; for (int i = 1; i < array2.length; i++) { array3[array2[i][0]][array2[i][1]] = array2[i][2]; } System.out.println("还原稀疏数组"); for (int[] ints : array3) { for (int anInt : ints) { System.out.print(anInt + "\t"); } System.out.println(); } }
五 面向对象OOP
5.1 方法回顾
方法的调用
public class Demo02 { public static void main(String[] args) { new Demo02().add(1,3); } public int add(int a,int b){ return a+b; }
public class Demo02 { public static void main(String[] args) { int add = Demo02.add(1, 3);//Demo02.add() alt+enter System.out.println(add); } public static int add(int a,int b){ return a+b; }//静态方法 直接通过类.方法 调用 }
类
public class Demo01 { public static void main(String[] args) { Student student = new Student(); //new Student() alt+enter student.say(); } }
值传递 引用传递
//值传递 public class Demo03 { public static void main(String[] args) { int a= 1; System.out.println(a); //1 change(a); System.out.println(a); //1 } public static void change(int a){ a = 10; } }
//引用传递 对象 本质还是值传递 public class Demo04 { public static void main(String[] args) { Person person = new Person(); //NEW 创建一个对象 System.out.println(person.name); //null Demo04.change(person); System.out.println(person.name); //fxh } public static void change(Person person){ //person是一个对象 指向的Person person = new Person(); 是一个具体的人 可以改变属性 person.name = "fxh"; } } //定义一个person类 class Person{ String name; }