文章目录
数组概述
数组声明创建
数组的四个基本特点
内存分析
理解
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10
at Demo15.main(Demo15.java:5)
数组越界
数组越界
三种初始化
动态初始化:包括默认初始化
数组使用
普通的for循环
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
}
for-Each循坏(没有下标)
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
for (int array : arrays) {
System.out.println(array);
}
}
数组作方法入参
数组作返回值
多维数组
Arrays类
冒泡排序
冒泡排序代码
public static void main(String[] args) {
int[] arr = {12,4,3,23,244,32,1,43,35};
int temp = 0;
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0;j< arr.length-1-i ;j++){
if (arr[j+1] < arr[j]){
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
代码优化
public static void main(String[] args) {
int[] arr = {12,4,3,23,244,32,1,43,35};
int temp = 0;
for (int i = 0; i < arr.length-1; i++) {
boolean flag = false;
for (int j = 0;j< arr.length-1-i ;j++){
if (arr[j+1] < arr[j]){
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
flag = true;
}
if (flag == false){
break;
}
}
}
}
稀疏数组
介绍
二维数组跟稀疏数组的转换
代码
public static void main(String[] args) {
// 上图,二维数组转为稀疏数组
int[][] arr1 = new int[6][7];
arr1[0][3] = 22;
arr1[0][6] = 15;
arr1[1][1] = 11;
arr1[1][5] = 17;
arr1[2][3] = -6;
arr1[3][5] = 39;
arr1[4][0] = 91;
arr1[5][2] = 28;
//sum存放有效值
int sum = 0;
System.out.println("输出原始数组");
for (int[] ints : arr1) {
for (int a : ints){
System.out.print(a+"\t");
if (a != 0){
sum++;
}
}
System.out.println();
}
System.out.println("=================");
System.out.println("转换为稀疏数组");
System.out.println("=================");
int[][] arr2 = new int[sum+1][3];
//存放行
arr2[0][0] = 6;
//存放列
arr2[0][1] = 7;
//存放有效值
arr2[0][2] = sum;
//临时变量,存放稀疏数组
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
if (arr1[i][j] != 0){
count++;
arr2[count][0] = i;
arr2[count][1] = j;
arr2[count][2] = arr1[i][j];
}
}
}
System.out.println("输出稀疏数组");
System.out.println("=================");
for (int[] ints : arr2) {
for (int a : ints){
System.out.print(a+"\t");
}
System.out.println();
}
//还原数组
//arr3 为还原数组
int[][] arr3 = new int[arr2[0][0]][arr2[0][1]];
for (int i = 1; i < arr2.length; i++) {
arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2];
}
System.out.println("输出还原的二维数组");
System.out.println("=================");
for (int[] ints : arr3) {
for (int a : ints){
System.out.print(a+"\t");
}
System.out.println();
}
}
效果图