定义数组
//动态初始化
dataType[] arrayName = new dataType[arraySize];
//静态初始化
dataType[] arrayName = {1, 2, 3, 4};
//二维数组
int[][] array = {{1, 2}, {3, 4}, {5, 6}};
例1:反转数组
public class Demo01 {
public static void main(String[] args) {
//反转数组
Demo01 demo01 = new Demo01();
int[] testArray = {1, 2, 3, 4, 5};
int[] result = demo01.reverse(testArray);
printArray(result);
}
public int[] reverse(int[] arrays){
int[] results = new int[arrays.length];
for (int i=0, j=arrays.length-1; i<arrays.length; i++, j--) {
results[i] = arrays[j];
}
return results;
}
public static void printArray(int[] arrays){
for(int i=0; i<arrays.length; i++){
System.out.print(arrays[i] + " ");
}
}
}
Arrays数组
所有方法可查看JDK帮助文档
import java.util.Arrays;
public class ArrayDemo01 {
public static void main(String[] args) {
int[] array = {1, 23, 4, 234, 12, 111};
//打印数组
System.out.println(Arrays.toString(array));
//数组排序
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}
例1:冒泡排序
public class Demo02 {
public static void main(String[] args) {
int[] a = {1, 4, 5, 2, 3, 54, 6};
int[] result = sort(a);
System.out.println(Arrays.toString(result));
}
public static int[] sort(int[] arrray) {
int temp = 0;
for (int i = 0; i < arrray.length-1; i++) {
for (int j = 0; j < arrray.length-1-i; j++) {
if (arrray[j] > arrray[j+1]){
temp = arrray[j+1];
arrray[j+1] = arrray[j];
arrray[j] = temp;
}
}
}
return arrray;
}
}