3.数组
一维数组
声明
package org.example;
public class Main{
public static void main(String[] args) throws Exception
{
int[] a = new int[5];
float[] b = new float[10];
char[] c = new char[3];
double[] d = new double[4];
}
}
初始化
package org.example;
public class Main{
public static void main(String[] args) throws Exception
{
int[] a = new int[5]; //未初始化,则为0
double[] b = {1.0, 2.0, 3.0};
char[] c = {'a', 'b', 'c'};
//也可:
double d[] = {1.0, 2.0, 3.0};
}
}
多维数组
声明与初始化
二维数组即数组元素为一维数组。注意:一维数组的长度不一定要相同,见下面
d
变量,
package org.example;
public class Main{
public static void main(String[] args) throws Exception
{
//声明
int[][] a = new int[3][4];
int[][][] b = new int[3][4][5];
//初始化
int[][] c = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
//注意:可以不一样长
int[][] d = {
{1, 2, 3, 4},
{5, 6, 7},
{8, 9, 10, 11}
};
}
}
范围遍历
package org.example;
public class Main{
public static void main(String[] args) throws Exception
{
int[][] d = {
{1, 2, 3, 4},
{5, 6, 7},
{8, 9, 10, 11}
};
//范围遍历
for(int[] row : d)
{
//此处的row变量是一个数组了
for(int x : row)
{
System.out.printf("%d ", x);
}
System.out.println("");
}
}
}
常用API
- 属性
length
:获取数组长度
以下
Arrays
相关函数注意需要:import java.util.Arrays;
-
Arrays.sort()
:数组排序 -
Arrays.toString()
:数组转化为字符串 -
Arrays.deepToString()
:多维数组转化为字符串 -
Array.fill(int[] a, int val)
:填充数组
示例如下:
package org.example;
import java.util.Arrays;
public class Main{
public static void main(String[] args) throws Exception
{
int[][] d = {
{7, 8, 1, 2, 10},
{5, 2, 0},
{6, 7, 10, 1}
};
//可以自定义排序方式,使用匿名函数
Arrays.sort(d, (x, y) -> {
return x[0] - y[0];
});
//多维数组输出
System.out.println(Arrays.deepToString(d));
//一维数组输出
System.out.println(Arrays.toString(d[0]));
}
}
下列补充一下自定义排序:
import java.util.Scanner;
import java.util.Arrays;
//需要实现该接口
class Group implements Comparable<Group>
{
private int x;
private double y;
private String z;
public Group(int x, double y, String z)
{
this.x = x;
this.y = y;
this.z = z;
}
public void print()
{
System.out.printf("%d %.2f %s\n", x, y, z);
}
//需要实现这个函数才能排序
//小于返回负数
public int compareTo(Group g)
{
return x - g.x;
}
}
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Group[] gs = new Group[n];
for(int i = 0; i < n; i ++)
{
int x = sc.nextInt();
double y = sc.nextDouble();
String z = sc.next();
gs[i] = new Group(x, y, z);
}
//使用Arrays排序
Arrays.sort(gs);
for(int i = 0; i < n; i ++)
gs[i].print();
}
}