Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this array?

Tags:

java

arrays

I come across this code line in a book and it said this is legal , but I don't really understand though having googling. the code is:

Boolean [] ba [];

I just know that to create an array, it should be like this:

int [] numberArray;

int numberArray [];

int [] [] num2DArray;

Thanks!

like image 534
Huy Than Avatar asked Aug 26 '12 07:08

Huy Than


People also ask

What is array explain?

An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Five values of type int can be declared as an array without having to declare five different variables (each with its own identifier).

What is an array with example?

An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[100];

What are the 3 types of arrays?

There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.

What is an array and types of array?

An array type is a user-defined data type consisting of an ordered set of elements of a single data type. An ordinary array type has a defined upper bound on the number of elements and uses the ordinal position as the array index.


1 Answers

All those 3 declarations have the same meaning in java :

Boolean  [][] ba ;
Boolean  [] ba [];
Boolean  ba [][] ;

I don't really like it but as there aren't any confusion possible, there is no very big harm in letting them be equivalent. The rationale was that C and C++ coders were used to a certain notation :

 int a[];

while the recommendation in java is to consistently declare the type before as in

 int[] a;

Here's the reference : http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.2

And two extracts :

Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rules for variable declaration, however, permit brackets to appear on both the type and in declarators, so that the local variable declaration

[...]

We do not recommend "mixed notation" in an array variable declaration, where brackets appear on both the type and in declarators.

In order to be more readable in Java, I suggest you stick to the usual

 Boolean[][] ba ;

Note that you have a similar behavior for method declarations. Here's an excerpt from the ByteArrayOutputStream class source code:

public synchronized byte toByteArray()[] {
    return Arrays.copyOf(buf, count);
}

This is allowed for compatibility but please don't use that. Most coders at first sight wouldn't notice the [] and thus wouldn't immediately read that this method returns an array.

like image 177
Denys Séguret Avatar answered Oct 03 '22 23:10

Denys Séguret