初识JAVA---数组(3)

数组定义与数组元素分配空间  分开进行

int []a=new int[3]

a[0]=3;

a[1]=9;

a[2]=8;

与C++ C 不同 Java中声明数组不要指定它的长度

int a[5]这是不对的

数组是引用类型

int []a=new int[5]  这里  a就是一个引用

静态初始化  定义数组时候就赋值

 int[] a={9,8,7};  或  int[] a=new int[]{3,9,8};

MyDate[] dates={

     new MyDate(22,7,1964),

     new MyDate(1,1,2000),

     new MyDate(22,12,1964)

} //最后可以多一个逗号  如{3,9,8,}

JAVA中数组分配空间用new   分配了空间的每一个元素都自动赋值0或者null  

每个数组都有一个函数length来指明数组的长度,a.length指明数组元素的个数

Java中有一个加强的for循环 

int[] ages=new int[10];

for(int age :ages)

{

System.out.println(age);%只读的遍历模式

}

数组复制函数  System.arraycopy

int[] source={1,2,3,4,5,6};//原数组

int[] dest={10,9,8,7,6,5,4,3,2,1};//目的数组

System.arraycopy(source,0,dest,0,source.Length);

%原数组0位置开始复制source.Length个元素到dest,0的位置

数组复制中

  1. for循环,效率最低

  2. System.arraycopy() 效率最高

  3. Arrays.copyOf() 效率次于第二种方法

  4. Object.clone() 效率次于第二种和第三种

二维数组

int [][]a={{1,2},{3,4,0,9},{5,6,7}};

int[][]t=new int[3][];

t[0]=new int[2];

t[1]=new int[4];

t[2]=new int[3]; 多维数组得声明和初始化应从高维到低维得顺序进行。

发布了103 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39653453/article/details/103575694
今日推荐