0

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});

why not like

ArrayList<Charset> list = new ArrayList<Charset>(); 

initialize array :

char[] b = new char[5](); ?

Why they are different? Is it one of java philosophical nature or some reasons behind it ?

5 Answers 5

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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

1 Comment

It doesn't answer to the question, which focuses on the initialization
0

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.

2 Comments

@AlexWei : Right. I am not sure of it, but it is probable that this syntax hides a constructor call.
Array is a contigous collection of primitives/objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.