Arrays
- java.util.Arrays 类:该类包含用于操作数组的各种方法(如排序和搜索);
1. 数组的创建
- 数组一旦创建无法修改长度,不建议用来增删改查;
- 数组在堆中创建,动态初始化时,数组元素由系统分配默认值;
a. 默认值
- byte/short/int/long:默认0;
- float/double:默认0.0;
- char:默认空字符;
- String:默认null;
- boolean:默认false;
2. 常用方法
类型 | 方法 | 说明 |
---|
void | sort(int[] a) | 按照数字顺序排列指定的数组 |
String | toString(int[] a) | 返回指定数组的内容的字符串表示形式 |
3. 数组的访问
a. 遍历
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int[] arr = new int[]{11, 22, 33};
for (int x = 0; x < arr.length; x++) {
System.out.print(arr[x] + " ");
}
System.out.println();
for (int n : arr) {
System.out.print(n + " ");
}
System.out.println();
System.out.println(Arrays.toString(arr));
}
}
b. 插入
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int[] arr = new int[]{11, 22, 33};
int number = 25;
int[] arr2 = new int[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
arr2[i] = arr[i];
}
arr2[arr2.length - 1] = number;
Arrays.sort(arr2);
System.out.println(Arrays.toString(arr2));
}
}
c. 反转
public static void reverse(int[] arr) {
for (int start = 0, end = arr.length - 1; start <= end; start++, end--) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
d. 交换元素(泛型方法)
public class test {
public static void main(String[] args) {
String[] str = {"a", "b", "c"};
swap(str, 0, 2);
for (String s : str) {
System.out.print(s + " ");
}
System.out.println();
Integer[] arr = {1, 8, 9, 5, 7};
swap(arr, 0, 2);
for (Integer i : arr) {
System.out.print(i + " ");
}
}
static <T> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
原文链接:https://qwert.blog.csdn.net/article/details/104488587