Tuesday, 17 May 2011

Anonymous Arrays in java

You can even initialize an anonymous array:

new int[] { 17, 19, 23, 29, 31, 37 }


This expression allocates a new array and fills it with the values inside the braces. It counts the number of initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable. For example,

smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };

is shorthand for

int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;

Note Inefficiency. Be careful not to create these anonymous arrays in a loop or as local variables because each use of new will create another array.


No comments:

Post a Comment