I have an array and I set to this array random values. I want to be to be sure that this array is full (there is a number in each position).How can I ensure about this? I wrote the following code but I’m not sure.
public boolean check(){
boolean checks=false;
int [] array =new int [10];
if(array.length==10){
checks = true;
}
return checks;
}
Arrays always have a value at each position, though those values might not be values that you’ve set. The code you have above will always set
checktotrue(assuming, of course, that you don’t get a memory exception when you allocate the array), since if you ask for an array of length 10 that’s precisely what you’re going to get. You might want to change those values later by doing some sort offorloop over them generating random values, but if you ask for space for 10 elements you don’t have to worry that your array will have some sort of “hole” in it where there isn’t any space.Similarly, there’s no way to check whether you’ve ever assigned to some array location or whether it’s still holding the default value. You will have to manage this yourself. That said, if you do a for loop like this one:
You can guarantee that every element of the array has had a value assigned to it.
Hope this helps!