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
posted
0
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: 3011
9
posted
0
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: 409
posted
0
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
posted
0
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
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.