数组的三种声明方式总结、多维数组的遍历、Arrays类的常用方法总结
作者:互联网
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()方法
1 @SafeVarargs 2 public static <T> List<T> asList(T... a) { 3 return new ArrayList<>(a); 4 }
使用该方法可以返回一个固定大小的List,如:
1 List<String> stringList = Arrays.asList("Welcome", "To", "Java", 2 "World!"); 3 4 List<Integer> intList = Arrays.asList(1, 2, 3, 4);
3.2 copyOf()及copyOfRange方法
1 String[] names2 = { "Eric", "John", "Alan", "Liz" }; 2 3 4 //[Eric, John, Alan] 5 String[] copy = Arrays.copyOf(names2, 3); 6 7 //[Alan, Liz] 8 String[] rangeCopy = Arrays.copyOfRange(names2, 2, 9 names2.length);
3.3 sort()方法
1 String[] names = { "Liz", "John", "Eric", "Alan" }; 2 //只排序前两个 3 //[John, Liz, Eric, Alan] 4 Arrays.sort(names, 0, 2); 5 //全部排序 6 //[Alan, Eric, John, Liz] 7 Arrays.sort(names);
另外,Arrays的sort方法也可以结合比较器,完成更加复杂的排序。
1 public static <T> void sort(T[] a, Comparator<? super T> c) { 2 if (LegacyMergeSort.userRequested) 3 legacyMergeSort(a, c); 4 else 5 TimSort.sort(a, c); 6 }
3.4 toString()方法
Arrays的toString方法可以方便我们打印出数组内容。
如:
String[] names = { "Liz", "John", "Eric", "Alan" }; Arrays.sort(names); System.out.println(Arrays.toString(names));
控制台将打印出 [Alan, Eric, John, Liz]
标签:总结,String,Arrays,Alan,names,数组,new 来源: https://www.cnblogs.com/zyx110/p/10622685.html