注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 可扩展、高可用、负载均衡..
 帮助

Java中的数组使用


2007-12-24 12:49:22
 标签:Java 数组 编程   [推送到技术圈]

1.  创造数组(Creating an array)
 
对于基本数据类型(int, float, char):
 
int carrot [];                    //不要在[ ]中加数字
carrot = new int [256];
 
这等价于
int carrot [] = new int [256];
 
这之后, 我们就可以给数组中的元素赋值, 例如
carrot[5] = 42;
 
但是对于引用类型, 创造数组之后, 我么只得到一个引用数组, 所以我们必须先要使每个引用指向一个对象(object), 这又叫作 instantiate the elements in array. 例如:
 
Fruit carrot [] = new Fruit [256];
for (int i = 0; i < carrot.length; i++)
{
     carrot[i] = new Fruit();  //通过构造函数, 使reference
}                                      //指向对象
 
2. 初始化数组(initializing an array)
    初始化同时, 数组的长度将会被自动指定.
 
int b[ ] = new int [ ] {1, 2, 2, 3, 5};
Fruit apple[ ] = new Fruit [ ] {new Fruit(), new Fruit(4, 3), null};
 
3. 数组的数组(arrays of arrays of ...)
Java中只存在数组的数组(arrays of arrays), 不存在多维数组(multidimensional arrays).
 
创造:
Fruit apple [ ] [ ];
apple = new Fruit [15] [6];
apply[i] = new Fruit [17];
apply[i][j] = new Fruit();
 
初始化:
int a [][] = new int [][]{
                                  {0},  
                                  {0, 1}
                                 }
 
int a [][] = new int [2][ ];
a[0] = new int [] {0};     // a[0].length equals to 1
a[1] =  new int[] {0, 1}; // a[1].length equals to 2
 
这里显示出了Java里面包括的是数组的数组, 而不是多维数组. 因为处于低维的各个数组是独立的, 可以具有不同的length.
 


上一篇 Java中J2SE,J2EE,J2ME  下一篇 FLTK 简介



    文章评论
 
2007-12-24 14:21:31
知识啊 学习了

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: