initialize java array vs other initialization?

后端 未结 5 1134
太阳男子
太阳男子 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:30

    ArrayList is a container, it's similar as Vector in C++, it can add and remove elements, but array can't change its size

    0 讨论(0)
  • 2021-01-28 05:38

    I guess the guys who created Java wanted to keep a syntax close to the C syntax. In Java, arrays are minimalist low-level objects, so their case is a bit particular.

    0 讨论(0)
  • 2021-01-28 05:39

    Arrays and ArrayList are used for different purposes. If you need a fixed size collection of objects then go for array but if you need dynamically growing collection of objects then go for arraylist. In some way compiler need to know about what is your need, hence the syntax is different.

    0 讨论(0)
  • 2021-01-28 05:46

    That's is simply design of Java. ArrayList and Arrays are two different things. No need to be same declaration.

    0 讨论(0)
  • 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<T> = new ArrayList<T>();
    

    Basically, arrays and classes just work in different ways.

    0 讨论(0)
提交回复
热议问题