java中Array(數組)的用法


8.Array(數組)   

數組是作為對象來實現的。(really occupy the memopry,真實的占用內存 )

An array is a data structure that stores a collection of value of the same type.(數組是一個數據結構,它存儲一堆類型相同的值)

/*下面這句話只是宣稱了一個參考類型的變量,而並沒有真正初始化,this statement just declares the reference type variables, not yet initialize*/
int[] a;
string[] b;
char[] c;
/*下面這句話真正初始化了,也就是真正給數組分配了內存,Initialize: Allocate memory for the array.*/
a = new int[10];
b = new String[3];
c = new char[20];

int[] a;
a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
System.out.println("the value of a[1] = " + a[1]);
a[1] = 100;
System.out.println("the value of a[1] = " + a[1]);

Initailizer(以下為另一種初始化數組的方法)
int[] a = {1,3,5,7,9};
Array length(數組的長度)
int i=a.length;//5


舉例:
int array_int[ ];
String[ ] str;
利用new 來為數組型變量分配內存空間
array_int=new int[10];
str=new String[10];
兩步可以合並,如:
String[ ] str=new String[10];

可以在它的length實例變量中找到一個數組的大小——也就是,一個數組能保存的元素的數目 。
所有的數組都有這個變量,並且它總是保存數組的大小。 

8.1 數組的length

Length:數組的容量,而不是數組實際存儲的元素的個數(mark, during initialization, 
the value of the array is initialized to 0, if the array 類型 is integer
)
 

// This program demonstrates the length array member.
class Length {
    public static void main(String args[]) {
        int a1[] = new int[10];
        int a2[] = {3,5,6,1,8,45,44,-10};
        int a3[] = {4,3,2,1};
        a1[1]=8;

        System.out.println("length of a1 is " + a1.length);
        System.out.println("length of a2 is " + a2.length);
        System.out.println("length of a3 is " + a3.length);
    }
}

J:\java教程>java Length
length of a1 is 10
length of a2 is 8
length of a3 is 4

更多內容請見原文,原文轉載自: https://blog.csdn.net/qq_43650923/article/details/101602752


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM