《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]); } }}相关文章推荐
- 《Java 编程技巧1001条》 第389条: 了解不平衡数组
- 《Java 编程技巧1001条》 第400条: 使用数组复制
- 《Java 编程技巧1001条》 第404条: 了解实用方法
- 《Java 编程技巧1001条》 第394条: 数组分类(排序)
- 《Java 编程技巧1001条》 第392条: 了解2分查找
- 《Java 编程技巧1001条》 第395与396条 :了解和使用冒泡排序
- 《Java 编程技巧1001条》 第387条: 建立多维数组
- 《Java 编程技巧1001条》 第397+398条:了解和使用快速排序
- 《Java 编程技巧1001条》第401条:数组中存不同对象
- 《Java 编程技巧1001条》 第390条: 初始化多维数组
- 《Java 编程技巧1001条》 第384条: 建立对象数组..
- 《Java 编程技巧1001条》第391条: 在数组中查找一指定值
- 《Java 编程技巧1001条》 第388条: 遍历多维数组
- 《Java 编程技巧1001条》 第399条:对原始类型数组使用数组复制
- 《Java 编程技巧1001条》第402-406条: 了解事件驱动程序,
- 《Java 编程技巧1001条》第414条:了解键盘事件
- 《Java 编程技巧1001条》 第385条: 了解多维数组
- 《Java 编程技巧1001条》 第403条: 了解事件类
- 《Java 编程技巧1001条》第412条...: 了解多按钮鼠标问题
- 《Java 编程技巧1001条》 第386条: 声明多维数组