数组的定义
- 数组是相同类型数据的有序集合
- 数组描述的是相同数据类型的若干个数据,按一定的先后次序排列组合而成
- 其中,每一个数###据称作一个数组元素,每个数组元素都可以用下标来访问
数组的创建
datatype[] var = new datatype[length]; // 推荐
datatype var[] = new datatype[length]; // 不推荐,这种格式是为了C/C++程序员适应Java
Java内存简介(其实分了5个区,要深入的话去了解JVM)
数组内存图解
数组的特点
- 数组一旦被创建,其长度就是确定的且不可改变
- 元素必须是同一类型
- 数组变量属于引用类型,数组实际上也是一个对象,数组中的每个元素相当于成员变量
- 数组可以当作是一个数据类型在方法中进行使用
多维数组
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一维数组,其每一个元素都是一个一维数组
Arrays类
- 数组工具类java.util.Arrays
- 由于数组对象本身并没有提供什么方法供我们调用,因此API给我们提供了个数组工具类,来对数组进行一些基本的操作
- 常用的静态方法:
- sort:对数组进行排序,默认升序
- binarySearch:对排序好的数组进行二分查找
- toString:将数组元素转换成特定格式的字符串表示形式
稀疏数组
- 需求:编写五子棋游戏中,有存盘和续上盘的功能
- 分析:该二维数组中的0都是没有用的数据
- 解决:稀疏数组
稀疏数组介绍
- 当一个数组中大部分元素为0或者同一值时,可以用稀疏数组来保存
- 稀疏数组的处理方式是:
- 创建一个小规模数组
- 数组一共几行几列,有多少个不同值记录在小规模数组的0号元素
- 把具有不同值的元素的行列及值依次记录在小规模的数组的剩下元素中,从而降低程序的空间复杂度
public class FiveChess {
private static int row = 11, col = 11;
private static int[][] chessBoard = new int[row][col]; // 建原始棋盘 1:白子 2:黑子
// 下棋
static void playChess(int row, int col, int value) {
chessBoard[row][col] = value;
}
// 压缩棋盘
static void compress() {
// 统计有多少个棋子
int count = 0;
for (int[] ints : chessBoard) {
for (int anInt : ints) {
if (anInt != 0)
count++;
}
}
// 建压缩棋盘
int[][] newChessBoard = new int[count+1][3];
newChessBoard[0][0] = row;
newChessBoard[0][1] = col;
newChessBoard[0][2] = count;
// 存棋子
count = 0;
for (int i = 0; i < chessBoard.length; i++) {
for (int j = 0; j < chessBoard[i].length; j++) {
if (chessBoard[i][j] != 0) {
count++;
newChessBoard[count][0] = i;
newChessBoard[count][1] = j;
newChessBoard[count][2] = chessBoard[i][j];
}
}
}
chessBoard = newChessBoard;
}
// 还原棋盘
static void restore() {
int[][] newChessBoard = new int[(chessBoard[0][0])][(chessBoard[0][1])];
for (int i = 1; i < chessBoard.length; i++) {
newChessBoard[(chessBoard[i][0])][(chessBoard[i][1])] = chessBoard[i][2];
}
chessBoard = newChessBoard;
}
static void printChessBoard() {
for (int[] ints : chessBoard) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
playChess(1, 2, 1);
playChess(2, 3, 2);
System.out.println("原棋盘");
printChessBoard();
System.out.println("===============================================");
System.out.println("压缩棋盘");
compress();
printChessBoard();
System.out.println("===============================================");
System.out.println("还原棋盘");
restore();
printChessBoard();
}
}