• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array construction - Belts and Braces?

 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

What is this code driving at?



I was awre you could do:

A) int[] x = new int[2];//default values of 0

and

B) int[] x = {1,2}; // Creates new aray object, referenced by x AND specifies values of x[0]==1 & x[1]==2.

But, why allow:

C) int[] x = new int[]{1,2};

What is this doing over and above B)?

Cheers,

Si.
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Simon Cockayne:
Hi, .....
B) int[] x = {1,2}; // Creates new aray object, referenced by x AND specifies values of x[0]==1 & x[1]==2.

But, why allow:

C) int[] x = new int[]{1,2};

What is this doing over and above B)?



I don't think it's doing anything over and above B. B is just a shortcut version of C. Note that the right side of C does have value, though, like when you want to create an array on-the-fly to, f.e., pass into a method. See the second half of chap. 1 in the S&B book.
 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As far as i know:
int[] x = {1,2}; ---> indicates that x is a reference to an array having values {1,2}.

int[] x = new int[]{1,2}; ---> here first an array is created having values {1,2} and then assigns that array to the array reference variable x. See the difference here is that the array created having those values is still not having any reference, it is just assigned to the reference variable x. Thats why we call it as an anonymous array construction.

Hope u r clear
 
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is called ananymous array,
there are used to create just in time
arrays e.g when passing an array to a
method or constructor.
Check K&B on array initialization, it explains it well.
Cheers and hope it helps
 
reply
    Bookmark Topic Watch Topic
  • New Topic