aspose file tools*
The moose likes Java in General and the fly likes Finding elements of Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Finding elements of Array" Watch "Finding elements of Array" New topic
Author

Finding elements of Array

Raj Kumar Bindal
Ranch Hand

Joined: Apr 15, 2006
Posts: 417
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

Joined: Dec 13, 2006
Posts: 182
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

Joined: Aug 05, 2005
Posts: 3169
    
  10
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 ]

Joanne
Raj Kumar Bindal
Ranch Hand

Joined: Apr 15, 2006
Posts: 417
you mean to say it is impossible and there is no way to find the initialized elements.
Ådne Brunborg
Ranch Hand

Joined: Aug 05, 2005
Posts: 208
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 ]

Entia non sunt multiplicanda praeter necessitatem
 
 
subject: Finding elements of Array
 
Similar Threads
array manipulation
array of arrays with arraylist
Arrays
Programming help
Array