1、数组的定义
- 数组是有序数据的集合,数组中的每个元素具有相同的数组名和下标来做唯一标识。
2、数组的分类
- 一维数组
- 二维数组
- 多维数组
3、数组的优点
- 不使用数组定义100个整型变量:int i1,int i2,int i3...int i100;
- 使用数组:int i[100]
注意:上述代码是伪代码,下面将详细说明数组的使用。
4、数组的声明
- 声明形式一:type arrayName[];
- 声明形式二:type[] arrayName;
public static void main(String args[]) {
int[] score = null;// 数组的声明
score = new int[3];// 为数组开辟内存空间,实例化
// 数组下标是从0开始的
for (int i = 0; i < score.length; i++) {
score[i] = i * 2 + 1;
}
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
}
5、数组静态初始化
- 动态初始化,所有的内容不会具体指定,都是默认值。
- 静态初始化,在创建之初,直接指定其内容。
public static void main(String args[]) {
// 静态初始化
int[] score = { 1, 2, 3, 4, 5, 6 };// 数组的声明
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
}
6、数组的使用
public static void main(String args[]) {
int[] score = { 41, 52, 83, 34, 65 };
int max, min;
max = min = score[0];
for (int i = 0; i < score.length; i++) {
if (score[i] > max) {
max = score[i];
}
if (score[i] < min) {
min = score[i];
}
}
System.out.println("最大值:" + max);
System.out.println("最小值:" + min);
}
/**
* 冒泡排序(Java 经典面试算法)
* @param args
*/
public static void main(String args[]) {
int[] score = { 41, 52, 83, 34, 65 };
for (int i = 0; i < score.length - 1; i++) {
for (int j = i + 1; j < score.length; j++) {
if (score[i] < score[j]) {
int temp = score[i];
score[i] = score[j];
score[j] = temp;
}
}
}
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
}
7、二维数组声明内存分配介绍及使用
- 如果把一维数组看成是线性图形,那么二维数组就是一个平面图形。
- 二维数组的声明和一维数组类似,内存分配也是使用new关键字。
- 声明形式:type arrayName[][];
- 初始化:arrayName[][] = new type[行][列];
public static void main(String args[]) {
int[][] score = new int[5][5];
score[0][0] = 9;
score[0][3] = 8;
score[3][2] = 7;
for (int i = 0; i < score.length; i++) {
for (int j = 0; j < score[i].length; j++) {
System.out.print(score[i][j] + " ");
}
System.out.println();
}
}
public static void main(String args[]) {
int[][] score = { { 100, 90 }, { 67, 70 }, { 50, 78, 80 } };
for (int i = 0; i < score.length; i++) {
for (int j = 0; j < score[i].length; j++) {
System.out.print(score[i][j] + " ");
}
System.out.println();
}
}
注意:在日常开发中,二维数组使用情况比较少,熟悉即可。







网友评论