您的位置:首页 > 编程语言 > Java开发

《Java 编程技巧1001条》 第382+283条: 了解数组的长度和引用

2017-12-21 18:14 501 查看



《Java 编程技巧1001条》第10章 用数组存储数据 第382+383条 了解数组的长度和引用
 

382 Finding the Length of an Array
382 确定数组的长度

In Java, anarray is an object. The only member variable of an array object is the lengthvariable which contains the size of the array. You will find the array objectlength variable useful for looping through the elements of anthe array. Thelength variable is read only because the size of an array object cannot changeafter you create the array. The following code demonstrates the use of thelength variable within a for loop that cycles through all the elements of anarray:
在Java中,一个数组是一个对象. 数组对象中唯一的成员变量是长度变量,它的值就是数组的大小. 你将发现,数组对象的长度变量在访问每一数组元素的循环程序中有用. 长度变量是一个只读变量,因为一个数组的大小在你建立了之后就不能改变. 以下的程序说明了长度变量在一FOR循环中的用法,这个循环通过了一个数组的所有的元素:int myarray[] = { 1, 2, 3, 4, 5 }; for (int index=0; index < myarray.length;index++)  {    System.out.println(myarray[index]);  }
 

383Understanding Array References
383 了解数组的引用

As you havelearned, Java uses references to point to an object. Array references are nodifferent thant those that you use for other types of objects. For example, youcan point to one array object with an array reference, and later point toanother array object using the same reference. The following statements use themyarray reference to access two different arrays:正如你所了解的那样,Java靠引用来指示一个对象. 数组的引用和其它对象类型的引用没有什么不同. 例如,你可利用一个数组的引用来指向一个数组元素,然后利用同样的引用来指向数组其余的元素. 以下语句是对数组myarray的引用,并访问了2个不同数组:public classarrayReference {   static public void main(String args)    {       int myfirst[] = { 1, 2, 3, 4 };      int mysecond[] = { 5, 6, 7, 8, 9, 10 };      int myarray[];      myarray = myfirst;       System.out.println("FirstArray:");       for (int index=0; index <myarray.length; index++)        {          System.out.println(myarray[index]);        }       myarray = mysecond;       System.out.println("Second Array:");       for (int index=0; index <myarray.length; index++)        {          System.out.println(myarray[index]);        }   }}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: