数组
来源:互联网 发布:mac mini 外加散热器 编辑:程序博客网 时间:2024/05/24 03:51
数组在Java中要看作一个对象。
在Java中,可以顶一个数组并初始化数组内容:
int[] score = {90, 85, 55, 94, 77};
下面举例:
public class SimpleArray {public static void main(String[] args) {int[] score = {90, 85, 55, 94, 77};for(int i = 0; i < score.length; i++)System.out.printf("score[%d] = %d\n", i, score[i]);}}在上面例子中,在每次的i递增后,都会作为数组的索引指定以取出对应的数组值。
上例中使用了length这个数组对象的属性成员,在Java中数组是一个对象,而不是单纯的数据集合。数组对象的length属性成员可以取回数组的长度,也就是数组中的元素个数。
当定义一个数组时,其实就是在配置一个数组对象。实际上上面例子只是数组定义与初始化成员的一个简易定义方式,在Java中对象都是以new来配置内存空间,数组的使用也不例外。一个完整的数组定义方式如下所示:
int[] arr = new int[10];
在上面的定义中,会为arr配置可以存储10个int整数的空间,索引为0-9.
如果想要在使用new新增数组时一并指定初始值,则可以编写如下语句。这种方式不必指定数组长度:
int[] score = new int[] {90, 85, 55, 94, 77};
foreach与数组:
J2SE 5.0新增了foreach的语法,又称强化的for循环(Enhanced for Loop),其应用的对象之一是在数组的依次存取上。foreach的语法如下:
for(type element : array) { System.out.println(element)...}直接以实例的方式来说明:
在J2SE 5.0之前可以使用下面方式来依次存取数组中的元素:
int[] arr = {1, 2, 3, 4, 5};for(int i = 0; i < arr.length; i++) System.out.println(arr[i]);在J2SE 5.0中可以使用心得foreach语法,这么写:
int[] arr = {1, 2, 3, 4, 5};
for(int element : arr)
System.out.println(element);
每一次从arr中取出的元素,会自动设定给element,您不用自行判断是否超出了数组的长度,注意element的类型必须与数组元素的元素类型相同。
如果是对象,做法也类似。例如存取字符串数组,可以编写如下:
String[] names = {"caterpillar", "momor", "bush"};
for(String name : names)
System.out.println(name);
那么二维数组呢?基本上要是了解数组本身就是一个对象,自然就会知道如何存取了,例子如下:
int[][] arr = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
for(int[] row : arr) {
for(int element : row) {
System.out.println(element);
}
}
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 对于PowerDesigner生成sql语句中表和字段带引号的问题
- [MS SQL]除法运算结果为小数时显示0的解决方案
- Windows下编译Firefox
- 问菩萨为何倒坐,叹众生不肯回头
- org.springframework.web.context.ContextLoaderListener
- 数组
- xw总结4:jmmntsj
- 多重采样(MultiSample)下的FBO反锯齿
- Delphi中对TRichEdit控件的每一行设置不同的颜色
- Spring : OpenSessionInViewFilter 的配置及替代方案
- Lib USB 在vc6.0下的应用
- HDU - 1226 超级密码
- 理解js中的闭包
- C++ 程序员必读书目清单