• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

anonymous array size (define or not define?)

 
sarah mrinmoyee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In k&b book, its said that when using anonymous array, you do not use array size.

for example:

int[] anonymousArray;

new int[3]{someVal1, someVal2, someVal3}; // is illegal

but if i do this,

new int[2]; // it works fine.


So what is the catch?? Is it illegal to define size or recommended not to define?
I used as following:

public class MyAnonymous{

public void testMethod1(){
testMethod2(new int[2][]);

}


public void testMethod2(int[][] b){

...
}

public void main(Strings args[]){
//call to testMehtod1()
}


}


As far i understood if you define size and also use number of items {val1,val2} it does not compile.


Any idea guyz/gals??




- Sarah
 
Bhavesh Saraswat
Greenhorn
Posts: 18
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sarah,

at the time of initialization size of the array is used to create array object. There are two ways to define the size of the array -

-- one way is to define size in the square braces without defining any element at creation time.

-- another way is to define array elements and it automatically counts the size of array to be created. In this way size of the array should not be provided.

I hope you are clear with your ques.
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sarah,

As you can see in Array Declaration, Construction, & Initialization (Objective 1.3) there are three stages for their definitions.


Belongs to the declaration stage where size is not allowed.

Belongs to the construction of an array object where the size is mandatory.

Regards,
Dan


 
sarah mrinmoyee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Guys,

But isn't "new int[2]; " // here size is not mandatory if you 't provide values like new int {0,1,2 }.

Actually i was confused with the line "when you use anonymous array size should not be defined!" It should be like if you provide values to the array then don't use size. But i am fine with the array declaration and initialization.

Keep posting!
-sarah
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic