day4 - 数组

95 阅读1分钟

数组


数组的声明

int[] intArr = int[3];
intArr[0] = 0;
intArr[1] = 1;
intArr[2] = 2;

Array类

方法 介绍
Array.sort() 对指定的数组按数字升序进行排序。
Array.toString() 转成字符串
Array.copyOf() 复制指定的数组到一个新数组,并指定新数组的长度。

sort例子

简单使用

public class DemoArraysSort {
	public static void main(String[] args) {
		int[] ages= {33,18,37,55,3};
		Arrays.sort(ages);
		for(int i=0;i<ages.length;i++) {
			System.out.println(i+" "+ages[i]);
		}
	}
}

自定义comparator

leetcode两地调度问题 leetcode-cn.com/problems/tw…

public static int twoCitySchedCost(int[][] costs) {
    System.out.println("排序之前的sort");
    System.out.print(Arrays.deepToString(costs));
    Arrays.sort(costs, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            // 按照去A和去B的费用差值由小到大排序(去A比去B更省钱的程度)
            return o1[0] - o1[1] - (o2[0] - o2[1]);
        }
    });
    System.out.println("排序之后的sort");
    System.out.print(Arrays.deepToString(costs));
    int total = 0;
    int n = costs.length / 2;
    // 前一半的人去A市,后一半的人去B市
    for (int i = 0; i < n;i ++) total += costs[i][0] + costs[i + n][1];
    return total;
}

copyOf用法

public static void main(String[] args) {
    int[] ages = { 33, 18, 37, 55, 3 };
    int[] newArray1 = Arrays.copyOf(ages, 3);
    System.out.println("newArray1截取3: " + Arrays.toString(newArray1)); // [33, 18, 37]
    int[] newArray2 = Arrays.copyOf(ages, 8);
    System.out.println("newArray2截取8: " + Arrays.toString(newArray2)); // [33, 18, 37, 55, 3, 0, 0, 0]
}

使用 copyOf() 时,如果指定的副本数组的长度小于源数组的长度,后面的元素都将被截断。如果指定的副本数组的长度大于源数组的长度,多出的元素都将使用默认值(数组元素类型的默认值,int的默认值是0)。

数组元素的默认值

类型 默认值
String null
int 0
double 0.0
boolean false
Object null