java数组
数组基本概念
数组定义:相同类型数据的有序集合,通过下标访问数组中的数据元素,数组下标从0开始
数组创建:
- 必须先声明数组: int[] array = new int[arraySize]; //arraySize代表数组大小,数组一经声明,大小无法改变
- 使用new操作符创建数组
- 获取数组长度:array.length
数组初始化:
-
静态初始化(声明的时候直接赋值)
int [] a = {1,2,3};
Man[] mans = {new Man(1,1) , new Man(2,2)}
-
动态初始化:先声明,开辟内存空间,使用的时候再赋值
int [] a = new int[3];
a[0] = 1;
- 默认初始化:数组为引用类型,元素相当于实例变量,数组一经分配空间,每个元素也按照实例变量方式被隐式初始化
数组使用
示例:稀疏数组
- 第一个元素记录原数组一共几行几列,有多少个不同值
- 把具有不同值的元素的信息记录在小规模数组
/*
* 稀疏数组的生成与二维数组的转换(文件读取)完成了文件的写入操作,读取文件数据并生成稀疏数组(尚未完成)
* @author: JayZ
* @version: 1.0.0
**/
import java.io.*;
public class SparseArray {
public static void main(String[] args) throws IOException {
//创建一个原始的二维数组 11 * 11
//0:表示没有棋子, 1 表示黑子, 2 表示蓝子
int chessArr1[][] = new int [11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[3][4] = 2;
//输出原始的二维数组
System.out.println("原始的二维数组:");
for(int[] row: chessArr1) {
for(int data: row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
//将二维数组 转 稀疏数组
// 1. 先遍历二维数组, 得到非0数据的个数
int sum = 0;
for(int i = 0; i < 11; i++) {
for(int j = 0; j < 11; j++) {
if(chessArr1[i][j] != 0) {
sum++;
}
}
}
//2. 创建稀疏数组
int sparseArr[][] = new int[sum+1][3];
//给稀疏数组赋值
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
// 遍历二维数组,将非0值存放到稀疏数组 sparseArr
int count = 0;
for(int i = 0; i < 11; i++) {
for(int j = 0; j < 11; j++) {
if(chessArr1[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
//将稀疏数组保存到output.txt文件中
OutputStream os = null;
try {
os = new FileOutputStream("output.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(os);
// 输出稀疏数组的形式
System.out.println();
System.out.println("得到的稀疏数组为:");
for(int i = 0; i < sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
pw.println(sparseArr[i][0]+" " + sparseArr[i][1]+ " " + sparseArr[i][2]);
}
pw.close();
os.close();
File file = new File("output.txt");
if(! file.exists()){
System.out.println("对不起,不包含指定路径的文件");
}else{
//根据指定路径的File对象创建FileReader对象
try {
FileReader fr = new FileReader(file);
char[] data = new char[93]; //定义char数组
int length = 0;
while((length = fr.read(data))>0){ //循环读取文件中的数据
String str = new String(data,0,length); //根据读取文件的内容创建String 对象
System.out.println(str); //输出读取内容
}
fr.close(); //关闭流
System.out.println("输出从文件中读取的data:");
System.out.println(data);
System.out.println(data[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println();
// 将稀疏数组转换成原始数组
// 1. 先读取稀疏数组的第一行,根据读取的数据创建二维数组
int chessArr2[][] = new int [sparseArr[0][0]][sparseArr[0][1]];
// 读取稀疏数组的后几行数据(第二行开始),赋值给原始的二维数组
for(int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
// 输出恢复后的二维数组
System.out.println("恢复后的二维数组:");
for(int[] row: chessArr2) {
for(int data: row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}