java ->Arrays類

來源:互聯網
上載者:User

標籤:stat   sys   index   需要   類的方法   poi   arch   sea   bsp   

概念

此類包含用來運算元組(比如排序和搜尋)的各種方法。需要注意,如果指定數組引用為 null,則訪問此類中的方法都會拋出null 指標異常NullPointerException。

常用方法

sort方法,用來對指定數組中的元素進行排序(元素值從小到大進行排序)

//源arr數組元素{1,5,9,3,7}, 進行排序後arr數組元素為{1,3,5,7,9}

int[] arr = {1,5,9,3,7};

Arrays.sort( arr );

toString方法,用來返回指定數組元素內容的字串形式

int[] arr = {1,5,9,3,7};

String str = Arrays.toString(arr); // str的值為[1, 3, 5, 7, 9]

binarySearch方法,在指定數組中,尋找給定元素值出現的位置。若沒有查詢到,返回位置為-1。要求該數組必須是個有序的數組。

int[] arr = {1,3,4,5,6};

int index = Arrays.binarySearch(arr, 4); //index的值為2

int index2= Arrasy.binarySearch(arr, 2); //index2的值為-1

Arrays類的方法練習

定義一個方法,接收一個數組,數組中儲存10個學生考試分數,該方法要求返回考試分數最低的後三名考試分數。

public static int[] method(double[] arr){

    Arrays.sort(arr); //進行數組元素排序(元素值從小到大進行排序)

    int[] result = new int[3]; //儲存後三名考試分數

    System.arraycopy(arr, 0, result, 0, 3);//把arr數組前3個元素複製到result數組中

return result;

}

java ->Arrays類

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.