Java数组
- 声明创建
- 使用
- Arrays类
- 稀疏数组
声明创建与使用
public class methodDemo03 {
public static void main(String[] args) {
int [] nums; // 声明数组
nums = new int [10];// 创建数组
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
nums[3] = 4;
nums[4] = 5;
nums[5] = 6;
nums[6] = 7;
nums[7] = 8;
nums[8] = 9;
nums[9] = 10;
int sum = 0;
for (int i = 0; i < nums.length; i++){ // nums.length获取数组长度
sum += i;
}
System.out.println(sum);
}
}
内存分析
三种初始化
-
静态
int[] a = {1,2.3}; Man[] mans = {new Man(1,1),new Man(2,2)};
-
动态
int[] a = new int[2]; a[0] = 1; a[1] = 2;
-
默认初始化
Arrays类
-
数组的工具类 java.util.Arrays
其中常用:
1. 给数组赋值(填充):fill 方法
- 对数组排序:sort方法(升序)
- 比较数组: equals方法
- 查找数组元素:binarySearch方法对排序好的数组进行二分法查找
冒泡排序
public class methodDemo04 {
public static void main(String[] args) {
int[] a ={1,4,5,6,72,2,2,2,25,6,7} ;
int[] sort = sort(a);
System.out.println(Arrays.toString(sort));
}
public static int[] sort(int[] array){
int temp = 0;
//外层循环判断循环多少次
for (int i = 0; i < array.length-1; i++){
//内层判断大小如果前大于后则交换
for (int j = 0; j < array.length-1; j++){
if (array[j+1] > array[j]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
return array;
}
}
稀疏数组 *
- 当一个数组大部分元素相同或为0时使用
- 方法为
- 记录几行几列,有多少个不同值
- 把具有不同值元素和行列值记录在一个小规模数组中
public class arrayDemo05 {
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();
}
// 1.转化为稀疏数组 获取有效值个数
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);
//创建一个稀疏数列数组 (n行3列)
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 i = 0; i < array2.length; i ++){
System.out.println(array2[i][0]+"\t"
+ array2[i][1]+"\t"
+ array2[i][2]+"\t");
}
}
}