Question:
How to empty array contents?
Jack S
2009-06-02 15:43:21 UTC
I have arrays like this:
check[k]=new entry(cook,book,food);
How would i empty the contents of this after this user has inputted information into the elements?

i basically would like to know how to reset the array.

p.s i use dr java
Four answers:
2009-06-02 17:05:31 UTC
Hey when you initialize an array without giving value..

java compiler will initialize default values respect to the data type



for example



'\0' (null character)for character array.

0 for integer array.

false for boolean array.



So if you want to erase or reset array values just assign this values

to it....



then the array will looks like a newly created array.



But null keyword cannot be used for character or integer or boolean array.... it is used only for objects........





so to reset integer array..

do

for(int a=0;a
check[a]=0;

}



for character array do



for(int a=0;a
check[a]='\0';

}



for boolean array do

for(int a=0;a
check[a]=false;

}



i think it may helped you
2009-06-02 17:36:59 UTC
In java, the best way would be to set all of the array references to null. This would be done in a for loop, and would take O(n) time, so probably not terrible for your application (unless you have a huge array). Something like...



for (int i = 0; i < array.getlength(); i++)

array[i] = null;



If you have already declared a counter i, first for loop argument changes to i = 0. This basically says, for each element in the array, set that pointer to null (nothing).
Ender Wiggin
2009-06-02 15:58:46 UTC
Hmm. I don't know java, but in Visual Basic you use a "ReDim" statement. From what I hear Java and VB are similar, so it might look something like this:



ReDim check() as TYPE



Note: Don't use a Preserve (ReDim Preserve check() as TYPE), or whatever the Java equivalent is. That will keep the contents and just change the size
Matt
2009-06-02 16:39:45 UTC
check[k] = new DATA_TYPE[k];



or if you wanted, you could do



for(int i=0;i
check[i]=null;

}



but that may not work for all data types.



But the easiest way would deffinatly be to just asign the array a value of a new array of equal length


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...