数组的三种声明方式总结、多维数组的遍历、Arrays类的常用方法总结

时间:2022-03-03 09:07:53

1. 数组的三种声明方式

public class WhatEver {
public static void main(String[] args) {
//第一种 例:
String[] test1 = new String[6];
test1[0] = "数组0";
test1[1] = "数组1"; //第二种 例:
String[] test2 = {"数组0","数组1","数组2","...."}; //第三种 例:
String[] test3 = new String[]{"数组0","数组1","数组2","...."}; }
}

2.多维数组的遍历

//二维数组
public class Test1 {
public static void main(String[] args) {
int[] score1=new int[10];
int[][] score2;
String[][] names;
//二维数组的初始化
score2=new int[][]{{1,2,3},{3,4,5,6},{16,7}};//静态初始化
names=new String[6][5];//动态初始化方式一
names=new String[6][];//动态初始化方式二,一定要设置行数
names[0]=new String[5];//第一行中有5个元素
names[1]=new String[4];
names[2]=new String[7];
names[3]=new String[5];
names[4]=new String[8];
names[5]=new String[5];
System.out.println("第一行中的元素:"+names[1].length);
System.out.println(names.length);//打印的是二维数组有几行 //如何遍历二维数组
for(int m=0;m<score2.length;m++){//控制行数
for(int n=0;n<score2[m].length;n++){//一行中有多少个元素(即多少列)
System.out.print(score2[m][n]+" ");
}
System.out.println();
} } }

3.Arrays类的常用方法总结

3.1  asList()方法

 @SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}

使用该方法可以返回一个固定大小的List,如:

 List<String> stringList = Arrays.asList("Welcome", "To", "Java",
"World!"); List<Integer> intList = Arrays.asList(1, 2, 3, 4);

3.2  copyOf()及copyOfRange方法

 String[] names2 = { "Eric", "John", "Alan", "Liz" };

     //[Eric, John, Alan]
String[] copy = Arrays.copyOf(names2, 3); //[Alan, Liz]
String[] rangeCopy = Arrays.copyOfRange(names2, 2,
names2.length);

3.3  sort()方法

 String[] names = { "Liz", "John", "Eric", "Alan" };
//只排序前两个
//[John, Liz, Eric, Alan]
Arrays.sort(names, 0, 2);
//全部排序
//[Alan, Eric, John, Liz]
Arrays.sort(names);

另外,Arrays的sort方法也可以结合比较器,完成更加复杂的排序。

 public static <T> void sort(T[] a, Comparator<? super T> c) {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, c);
}

3.4  toString()方法

Arrays的toString方法可以方便我们打印出数组内容。 
如:

String[] names = { "Liz", "John", "Eric", "Alan" };
Arrays.sort(names);
System.out.println(Arrays.toString(names));

  

控制台将打印出 [Alan, Eric, John, Liz]