• Post Reply Bookmark Topic Watch Topic
  • New Topic

initialize array to non-default value  RSS feed

 
Marcus Kelvin
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the best practice for initializing an entire array to a single value, eg:



Is that it, or is there something more succinct?
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

In the Arrays class, you will find methods called fill(). Those might fit the bill for you.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, always use < myArray.length in the middle of a for loop to traverse your array. That way you can be assured of never going outwith the bounds of the array.
 
Marcus Kelvin
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers.



Does the trick.

One question about ray.length -- that's not a method, it's a value, which is good, but I don't see it documented on that oracle page for the "Arrays" class. Why not?
 
Sebanti Sanyal
Ranch Hand
Posts: 58
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'length' is a member variable,which every array object(e.g. int[],String[]) owns. It is not part of the utility class 'Arrays'.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It’s all the Java Language Specification. That isn’t always easy to understand, however.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Tutorials may be easier to understand.
 
Marcus Kelvin
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright. Thanks gang. Java seems quite nice so far.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!