1.一维数组
1.1一维数组的声明和初始化
//两种声明方式
int[] arry; //1---数组类型[] 数组名
int arry[]; //2---数组类型 数组名[]
//两种分配空间方式
arry = new int[3]; //1--- 数组名 = new 数组类型[元素个数]
arry = new int[]{1, 2, 3}//2--- 数组名 = new 数组类型 []{元素1, 元素2, ... 元素n}
//两种赋值方式
int[] arry;
arry = new int[3];
arry[0] = 1;
arry[1] = 2;
arry[2] = 3; //1--- 一个个赋值
int[] arry = new int[]{1, 2, 3}//2--- 一起赋值
1.2一位数组的访问
索引、length属性
//冒泡排序 public class Demo4_2 { public static void main(String[] args) { int[] arry1 = {78, -32, 2, 4, 89, 93, 25, 18, 17, 18, 65}; int ntemp = 0; System.out.println("原始数据如下:"); for (int i = 0; i < arry1.length; i++) { System.out.print(arry1[i] + " "); } for (int i = 0; i < arry1.length - 1; i++) { //循环遍历 for (int j = i; j < arry1.length - 1 - i; j++) { if (arry1[j] > arry1[j+1]) { //冒泡排序实现 ntemp = arry1[j+1]; arry1[j+1] = arry1[j]; arry1[j] = ntemp; } } } System.out.println("\n冒泡排序后数据如下:"); for (int i = 0; i < arry1.length; i++) { System.out.print(arry1[i] + " "); } } }
1.3数组的异常
ArryIndexOutOfBoundsxception (数组下标越界异常)
//遍历数组打印输出比平均值小者 public class Demo4_1 { public static void main(String[] args) { int[] arry1 = new int[] {1, 89, 90, 45, 75, 84, 29, 48, 93, 18}; double dbsum = 0; //第一次遍历求总值 for (int i = 0; i < arry1.length; i++) { dbsum = dbsum + arry1[i]; } double dbavg = dbsum/arry1.length; //第二次遍历选择输出 System.out.println("数组平均值为:"+ dbavg); for (int i = 0; i < arry1.length; i++) { if (arry1[i] < dbavg) { System.out.println("比数组平均值小的有:" + arry1[i]); } } } }
2.多维数组
2.1多维数组的定义与创建
3种声明方式(同一维的差不多)、多维数组的创建、2种赋值方式
2.2多维数组的遍历与访问
通过多层循环逐一遍历
//行列转置 public class Demo4_3 { public static void main(String[] args) { int[][] arry1 = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}}; int[][] arry2 = new int[3][3]; for (int i = 0; i < arry1.length; i++) { for (int j = 0; j < arry1[i].length; j++) { arry2[i][j] = arry1[j][i]; System.out.print(arry2[i][j] + " "); } System.out.print("\n"); } } }
3.数组相关操作
3.1数组的排序
import java.util.Arrays
排序方法:sort方法(2种形式全部排序和指定区间排序)
3.2数组的复制
copyOf方法(将数据复制到新的数组,新数组长度不小于原数组)
copyOfRange方法(将原数组指定区间数据进行复制形成新数组)
system.arraycopy()(将原数组固定长度的指定区间数据复制到新数组)