Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Finding elements of Array

 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an array of size 5 integers.
I have initialized 1st and third element with values 1 and 0.
Now,i want to find out which all elements have i put during initialization and which are empty initially.
please tell me how to do that.
 
Ajay Singh
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can first fill the array with some value (lets say 0, using method Arrays.fill(array, 0)) and then while initializing check if
the value is 0, if yes, the value at that index is not initialized.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int arrays automatically have all their elements set to zero, so if zero is a valid value, there is no way to check whether an element has been initialised or not - unless there is a value that you know you will never use, in which case you could initialise all elements to this when you create the array and then consider this as the uninitialised state.

You could use an Integer array. Object arrays have all their elements initialised to null.
[ January 12, 2007: Message edited by: Joanne Neal ]
 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you mean to say it is impossible and there is no way to find the initialized elements.
 
Ådne Brunborg
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Raj Kumar Bindal:
you mean to say it is impossible and there is no way to find the initialized elements.


All elements have already been initialized - they initialize to 0 the following line is executed:

will be initialized to [0,0,0,0,0].

If you need to distinguish which elements are initalized, and 0 is a valid value, you will need to either fill the array with an invalid value (e.g. -1), or use an Integer[] instead of an int[]:


Elements in an Integer[] will not be initialized - as in, they will be null:
[null,null,null,null,null]
[ January 12, 2007: Message edited by: �dne Brunborg ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic