开发者

Java: How do I check if an element in an array has been initialized?

I want to check if a certain element in 开发者_运维技巧an array has been initilized, how can I do this?


All values in an array are initialised when the array is created.

Initial values may be set explicitly (e.g. X[] xs = {x1, ..., xN};), or default values will be assigned when the array is instantiated.

For an array of objects, the default value of each element will be null; for a boolean array, the value will be false; for an array of byte, char, int, long the value will be 0 and for an array of float or double the value will be 0.0.


Well, you can check whether it's been set to not have the default value, e.g.

String[] array = getArrayFromSomewhere();
if (array[10] != null)
{
    ...
}

(For primitive types you'd use 0, '\0', false etc.)

However, that's not the same not being initialized. It could have been set to null after having been set to a different value.

Arrays keep no record of whether an element has been specifically set - the elements are all initialized to the default value, and that's all.


String[] X; // X has not been initialized

try {
    System.out.println(""+X.length); // This will crash if X is not initialized
} catch (NullPointerException e) { // X is empty
    System.out.println("X has not been initialized.");
    // Do whatever you want here with X
}


On top of already approved answer, you can verify with java9+ in jshell as it tells you the default index values.

primitive arrays

jshell> byte[] data = new byte[10]
data ==> byte[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

jshell> int[] data = new int[10]
data ==> int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

jshell> char[] data = new char[10]
data ==> char[10] { '\000', '\000', '\000', '\000', '\000' ... , '\000', '\000', '\000' }

jshell> boolean[] data = new boolean[10]
data ==> boolean[10] { false, false, false, false, false,  ... lse, false, false, false }

object arrays

jshell> String[] data = new String[10]
data ==> String[10] { null, null, null, null, null, null, null, null, null, null }


Simply way of checking is:

int[] ar = new int[10];

if (ar.length < 0) {
    System.out.println("Not initialized ");
} else {
    System.out.println("Initialized");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜