Java數組簡單用法

來源:互聯網
上載者:User

標籤:java   數組   

數組是具有相同資料類型的一組資料的集合,Java支援多為數組,一維數組的每個基本單元都是基礎資料型別 (Elementary Data Type)的資料,二維數組就是每個基本單元是一維數組的一維數組,以此類推,n維數組的每個基本單元都是n-1為數組的n-1維數組。下面以一維數組為例說明Java數組的用法。

1、數組聲明

數組聲明有如下兩種形式(方括弧的位置不同):

int arr[];int[] arr2;
2、數組初始化

數組初始化也有兩種形式,如下(使用new或不使用new):

int arr[] = new int[]{1, 3, 5, 7, 9};int[] arr2 = {2, 4, 6, 8, 10};
3、遍曆數組

遍曆數組可用for/foreach,如下:

    public static void main(String[] args) {        int arr[] = new int[]{1, 3, 5, 7 ,9};        int[] arr2 = {2, 4, 6, 8, 10};        for (int i = 0; i < arr.length; ++i) {            System.out.print(arr[i] + "\t"); // 1 3 5 7 9        }        for (int x: arr2) {            System.out.print(x + "\t"); // 2 4 6 8 10        }    }
4、Arrays.fill()填充數組

使用Arrays類的靜態方法,需要import包java.util.Arrays,定義了許多重載方法。

void fill(int[] a, int val)全部填充
void fill(int[] a, int fromIndex, int toIndex, int val)填充指定索引的元素

        int[] arr3 = new int[5];        for (int x: arr3) {            System.out.print(x + "\t"); // 0 0 0 0 0 全部初始化為0        }        System.out.println();        Arrays.fill(arr3, 10);        for (int x: arr3) {            System.out.print(x + "\t"); // 10 10 10 10 10 全部填充為10        }        System.out.println();        Arrays.fill(arr3, 1, 3, 8);        for (int x: arr3) {            System.out.print(x + "\t"); // 10 8 8 10 10 填充指定索引        }        System.out.println();
5、Arrays.sort()對數組排序

void sort(int[] a)全部排序
void sort(int[] a, int fromIndex, int toIndex)排序指定索引的元素

        int[] arr4 = {3, 7, 2, 1, 9};        Arrays.sort(arr4);        for (int x: arr4) {            System.out.print(x + "\t"); // 1 2 3 7 9        }        System.out.println();        int[] arr5 = {3, 7, 2, 1, 9};        Arrays.sort(arr5, 1, 3);        for (int x: arr5) {            System.out.print(x + "\t"); // 3 2 7 1 9        }        System.out.println();
6、Arrays.copyOf()複製數組

int[] copyOf(int[] original, int newLength)複製數組,指定新數組長度
int[] copyOfRange(int[] original, int from, int to)複製數組,指定所複製的原數組的索引

        int[] arr6 = {1, 2, 3, 4, 5};        int[] arr7 = Arrays.copyOf(arr6, 5); // 1 2 3 4 5        int[] arr8 = Arrays.copyOfRange(arr6, 1, 3); // 2 3        for (int x: arr7) {            System.out.print(x + "\t");        }        System.out.println();        for (int x: arr8) {            System.out.print(x + "\t");        }        System.out.println();

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java數組簡單用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.