Java多維數組和Arrays類方法總結詳解
一.數組的三種聲明方式總結
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','....'}; }}<br><br>
二.多維數組的遍歷/二維數組
/二維數組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(); } }}
三. Arrays類的常用方法總結
java.util.Arrays類能方便地操作數組,它提供的所有方法都是靜態的。
3.1 asList()方法
返回一個受指定數組支持的固定大小的列表。
此方法還提供了一個創建固定長度(不可修改的數組 同singletonList)的列表的便捷方法,該列表被初始化為包含多個元素:
List stooges = Arrays.asList('Larry', 'Moe', 'Curly');
@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方法
copyOf(int[] original, int newLength)復制指定的數組,截取或用 0 填充(如有必要),以使副本具有指定的長度。
copyOfRange(int[] original, int from, int to)將指定數組的指定范圍復制到一個新數組。
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); }
返回指定數組內容的字符串表示形式。
String[] arg = {'a', 'b', 'c', 'd'}; // 結果 [a, b, c, d]System.out.print(Arrays.toString(arg));
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: