一、一维数组的创建和使用
int arr[];
String str[];
arr = new int[5];
int month[] = new int[12];
二、二维数组的创建和使用
int myarr[][];
a = new int[2][4];
分配内存:
a = new int[2][];
a[0] = new int[2];
a[1] = new int[3];
二维数组的初始化:
int myarr[][] = {{12,0},{45,10}};
三、数组的遍历
遍历的第二种方法:
int myarr[][] = new int[2][3] ;
for(int x[]:myarr) {
for(int e:x){
System.out.print(e);
}
}
四、数组的基本操作
1、填充替换数组元素
fill(int[] a, int value)
例子:
import java.util.Arrays;
public class Displace{
public static void main(String[] args) {
int arr[] = new int[]{123,234,23};
Arrays.fill(arr, 8);
}
// 输出结果为 8 8 8
}
fill(int[] a,int fromIndex, int toIndex, int value)
例子:
import java.util.Arrays;
public class Displace{
public static void main(String[] args) {
int arr[] = new int[]{123,234,23,456};
Arrays.fill(arr, 1, 2, 8);
}
// 输出结果为 123 8 23 456
}
2、对数组进行排序
Arrays.sort(object);
声明:Java中String类型数组的排序算法是根据字典编排顺序排序的,因此数字排在字母前面,大写字母排在小写字母前面。
3、复制数组
copyOf(arr, int newlength)
用例:
import java.util.Arrays;
public class Cope{
public static void main(String[] args){
int arr[] = new int[]{23, 42, 12};
int newarr[] = Arrays.copyOf(arr, 5);
// 输出数组newarr 结果:
// 23 42 12 0 0
}
}
copyOfRange(arr, int fromIndex, int toIndex)
顾名思义
4、数组查询
Arrays类中binarySearch()方法可以使用二分搜索法来搜索指定数组。
用法:
binarySearch(Object[], Object key)
返回index,在搜索前记得 Arrays.sort(Obejcet);
binarySearch(Object[], int fromIndex, int toIndex, Object key)
五、数组排序算法
1、冒泡排序
2、直接选择排序
3、反转排序
课后练习
import java.util.Arrays;
public class Practice4_数组 {
public static void main(String[] args) {
// 复制数组练习
int arr1[] = new int[] {1,2,3,4,5};
int arr2[] = Arrays.copyOfRange(arr1, 0, 3);
for(int x:arr1) {
System.out.print(x);
}System.out.println();
for(int x:arr2) {
System.out.print(x);
}System.out.println();
// 输出数组最小元素
int arr3[] = new int[] {3,2,5,1,6,7};
Arrays.sort(arr3);
System.out.println(arr3[0]);
// 数组元素替换输出
String str[] = new String[] {"ab","bc","cd","de"};
String str2[] = Arrays.copyOf(str, str.length);
str2[2] = "bb";
for(String s:str) {
System.out.print(s);
}System.out.println();
for(String s:str2) {
System.out.print(s);
}System.out.println();
// 二维数组行列互调练习
int arr4[][] = new int[4][4];
int t = 1;
for(int i = 0 ; i < 4 ; i ++) {
for(int j = 0 ; j < 4 ; j ++) {
arr4[i][j] = t++ ;
}
}
for(int i = 0 ; i < 4 ; i ++) {
for(int j = 0 ; j < 4 ; j ++) {
System.out.print(arr4[i][j] + " ");
}System.out.println();
}
int arr5[][] = new int[4][4];
for(int i = 0 ; i < 4 ; i ++) {
for(int j = 0 ; j < 4 ; j ++) {
arr5[i][j] = arr4[j][i];
}
}
for(int i = 0 ; i < 4 ; i ++) {
for(int j = 0 ; j < 4 ; j ++) {
System.out.print(arr5[i][j] + " ");
}System.out.println();
}
}
}