三种定义数组的方式

方式一
数据类型[] 数组名字 = new 数据类型[长度];
[] : 表示数组,数组有定长特性,长度一旦指定,不可更改

int[] arr = new int[3];

方式二
数据类型[] 数组名 = new 数据类型[]{元素1,元素2,元素3…};

public static void methodA(String obj){
    
    
int[] arr = new int[]{
    
    1,2,3,4,5};
Object[] arr1 =  new Object[]{
    
    obj};
 //不要和创建对象混了
Object object = new Object();
 //数组作为方法参数
Logger.error(getClass(), MessageID.MAS004E, new Object[]{
    
    obj});
}

方式三
数据类型[] 数组名 = {元素1,元素2,元素3…};

int[] arr = {
    
    1,2,3,4,5};

总结
1.方式三虽然没有new关键字,但是jvm仍然要在内存中开辟空间。
2.数组的定义和初始化可以分为二个步骤,但是方式三不可以。

     //第一种
        int[] a;
        a = new int[3];//正确
        //第二种
        int[] b;
        b = new int[]{
    
    1, 2, 3};//正确
        //第三种
        int[] c;
        c= {
    
    1,3,4};//错误
        //第三种
        int[] d = {
    
    1,2,3};//正确

数组的访问
数组名[索引]

//定义存储int类型数组,赋值元素1,2,3,4,5
    int[] arr = {
    
    1,2,3,4,5};
    //为0索引元素赋值为6
    arr[0] = 6;

数组遍历:

public static void main(String[] args) {
    
    
    int[] arr = {
    
     1, 2, 3, 4, 5 };
    for (int i = 0; i < arr.length; i++) {
    
    
      System.out.println(arr[i]);
    }
}

猜你喜欢

转载自blog.csdn.net/djydjy3333/article/details/121306108