关于java数组length
新建java数组时有多种方法,可new或跟c一样只用声明,如int[] a;另外值得注意的一点是,length方法只能返回数组大小,但数组有可能是空的(int是为null,char时为(char)0,boolean时为false),可能是空的基本数据类型,也可能是空对象
class Weeble{}
public class ArraySize {
//private static Test monitor = new Test();
public static void main(String[] args){
Weeble[] a;
Weeble[] b = new Weeble[5];
Weeble[] c = new Weeble[4];
for(int i=0;i<c.length;i++)
if(c[i] == null)
c[i] = new Weeble();
Weeble[] d = {
new Weeble(), new Weeble(),new Weeble()
};
a= new Weeble[]{
new Weeble(),new Weeble()
};
System.out.println("a.length="+a.length);
System.out.println("b.length="+b.length);
for(int i=0;i<b.length;i++)
System.out.println("b["+i+"]="+b[i]);
System.out.println("c.length="+c.length);
System.out.println("d.length="+d.length);
a=d;
System.out.println("a.length="+a.length);
int[] e;
int[] f= new int[5];
int[] g= new int[4];
for(int i=0;i<g.length;i++){
g[i]=i*i;
}
int[] h={11,47,93};
// System.out.println("e.length="+e.length);
System.out.println("f.length="+f.length);
for(int i=0;i<f.length;i++){
System.out.println("f["+i+"]="+f[i]);
}
System.out.println("g.length="+g.length);
System.out.println("h.length="+h.length);
e=h;
System.out.println("e.length ="+e.length);
e=new int[] {1,2};
System.out.println("e.length="+e.length);
boolean[] q=new boolean[3];
System.out.println("q.length="+q.length);
for(int i=0;i<q.length;i++)
System.out.println("q["+i+"]="+q[i]);
char t[]= new char[3];
System.out.println("t.length="+t.length);
for(int i=0;i<t.length;i++)
System.out.println("t["+i+"]="+t[i]);
}
}
输出:
a.length=2
b.length=5
b[0]=null
b[1]=null
b[2]=null
b[3]=null
b[4]=null
c.length=4
d.length=3
a.length=3
f.length=5
f[0]=0
f[1]=0
f[2]=0
f[3]=0
f[4]=0
g.length=4
h.length=3
e.length =3
e.length=2
q.length=3
q[0]=false
q[1]=false
q[2]=false
t.length=3
posted on 2011-11-16 23:10 ywnbluesky 阅读(2613) 评论(0) 收藏 举报