initialize java array vs other initialization?

后端 未结 5 1133
太阳男子
太阳男子 2021-01-28 05:05

I know that when I initialize a char array: I have to

char[] b= new char[5];

or

char[] b= new char[5]({1,2,3,4,5});
         


        
5条回答
  •  隐瞒了意图╮
    2021-01-28 05:50

    If you've ever used C, then the answer is fairly simple. In C, the way you create arrays is by allocating a static length of memory on the stack that is large enough to contain the number of elements, and point to the first element with a pointer - or dynamic length of memory on the heap, and point to the first element with a pointer.

    int a[5]; //stack, static allocation
    
    int* a = (int*)malloc(sizeof(int)*5)); //heap, dynamic allocation
    

    And in C++, the second version was changed to this, obviously because it's more obvious what is happening:

    int* a = new int[5];
    

    And they took this type of array creation over to Java.

    int[] a = new int[5];
    

    Arrays don't really work like typical objects, hence why even creating them and manipulating them with reflection uses a different Array class in order to manipulate the object. (see http://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html )

    ArrayLists are different, because they're just everyday classes like most things in java, so you initialize them with an actual constructor call:

    List = new ArrayList();
    

    Basically, arrays and classes just work in different ways.

提交回复
热议问题