数组
声明一个数组 int[] nums
创建一个数组 nums = new int[10]
初始化
静态初始化:int[] a = {1,2,3,4,5}
动态初始化:nums = new int[10]
nums[0] = 10
数组的基本特点:
- 数组长度固定
- 元素必须是相同类型
- 数组内元素可以是任何类型
- 数组也是元素,数组元素相当于对象的成员变量
数组的使用
- For-Each循环
- 数组作方法入参
- 数组作为返回值(反转数组)
- 普通的for循环
For-Each循环
int[] arrays = {1,2,3,4,5};
for(int array : arrays){
System.out.println(array)
}
//没有下标
数组作为返回值(反转数组)
public class array {
public static void main(String[] args) {
int[] nums = {1,2,3,4,5};
int[] array = reverse(nums);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static int[] reverse(int[] arrays){
int[] result = new int[arrays.length];
for (int i = 0,j = arrays.length-1; i < arrays.length ; i++,j--) {
result[j] = arrays[i];
}
return result;
}
}
多维数组
public class array {
public static void main(String[] args) {
int[][] nums = {{1,2},{1,2},{1,2},{1,2}};
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
System.out.println(nums[i][j]);
}
}
}
}
冒泡排序:
public class array {
public static void main(String[] args) {
int[] nums = {1922,45,6,5,8,5,1,5456,8465,454,21};
int temp = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length-1-i; j++) {
if(nums[j+1]>nums[j]){
temp = nums[j+1];
nums[j+1] = nums[j];
nums[j] = temp;
}
}
}
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
}
稀疏数组
当一个数组中大部分元素为0或同一数值,可以使用稀疏数组来保存。
处理方式
- 记录一共有几行几列,有多少个不同值
- 把具有有效值的位置记录下来