Java基础练习题 (4)数组操作

时间:2023-02-23 12:17:33

(1)如何创建空数组?

int[] array = {};
int[] array = new int[]{};

如果是创建空集合呢?Collections 类有一个方法 emptyList(), 返回一个空 List,当然你可以直接 new 一个List也是一样的,只是 emptyList() 方法返回的 List 是被 final 修饰的。

(2)如何对数组进行排序?
java.util.Arrays 类包含很多对数组进行操作的方法,如排序、搜索等,排序我们可以使用 Arrays.sort()方法,

int[] array = {5, 3, 7, 1, 0, 88};
Arrays.sort(array);

这样 array 就会从小到大排好序了,当然这个 sort 方法还可以对其他类型进行排序,详情可以查阅文档。

(3)如何提取数组的一部分生成另一个数组?
使用 Arrays.copyOfRange 方法,有三个参数,第一个是要提取的数组,第二个是从哪里开始,第三个是到哪里结束且不包括该位置。

int[] array = {1, 2, 3, 4, 5};
int[] newArray = Arrays.copyOfRange(array, 0, 2);

newArray 就是 {1, 2},当然也可以自己写个循环来赋值,想当于重新写一个 copyOfRange 了。

(4)如何合并两个数组,同时使合并的数组中不包含重复的元素?
这里的前提条件应该是这两个数组本身不包含重复的元素。
暂时没想到较好的写法。

(5)如何在数组中用二分法搜索元素?
使用 Arrays.binarySearch 方法,

int[] array = {1, 2, 3, 4, 5};
int position = Arrays.binarySearch(array, 3);
System.out.println(position);

上面代码打印出 “2”, 就是 3 在数组 array 中的位置。注意传入的数组必须是已经排好序的,不然结果会不准确,了解二分查找的应该都知道。如果没有找到要找的元素,会返回什么呢?查阅文档,可以看到

Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

就是说如果没有找到,就返回 (-(insertion point) - 1),这个 insertion 就是对于被搜索的数组来说,要查找的元素会被放置的位置。比如说你在 {1, 3, 5} 中查找 2 ,会返回 (-(1) - ),也就是 -2,这里的 insertion = 1,因为 2 会放置在第二个位置。

随着 Java 版本的更新,越来越多的通用方法被加入进 jdk 里面,很多方法我们都不需要自己写了,也就是不用重复造*了,当然我们还是需要去了解这个方法的实现原理,这样我们才会有比较实际性的成长。

(6)如何将数组反转?
我在文档里貌似没看到可以直接反转的方法,所以就考虑自己写一个吧,这里以 int 数组为例

public void reverse(int[] array) {
int start = 0;
int end = array.length - 1;
while(start < end) {
int temp = array[start];

array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}

就是通过循环将头尾逐次交换。