如何获取不为null的数组元素 [英] How to get elements of an array that is not null
问题描述
我正在使用数组进行礼物(字符串型)存储,最大存储量为5亿个.我想获取数组中已使用元素的数量,例如当前有多少礼物,(即我存储了253538个礼物,但我不知道.Java中是否有一个命令可以知道只有253538个包含元素的数组中的插槽).但是我不知道该怎么办.这是我要使用的代码片段:
I am doing gift (String-type) storage, using arrays, with the maximum 500 million. I want to get the number of used elements in an array like how many gifts are currently in stock, (I.E. I stored 253538 gifts, but I don't know that. Is there a command in Java that can know that there is only 253538 Slots in the array that contain an element). But I don't know how to. Here's the snippet of code I want to use:
static String[] Gifts = new String[500000000];
static int i = 0;
String command, Gift;
while (true) {
//Gift Array Console
String command = scan.next();
if (command == "addgift") {
String Gift = scan.next();
Gifts[i] = Gift;
i++;
}
}
推荐答案
您可以遍历数组并计算已初始化的数组元素.
You can iterate through the array and count the initialized array elements.
int counter = 0;
for (int i = 0; i < arrayName.length; i ++)
if (arrayName[i] != null)
counter ++;
如果您使用 ArrayList< String>
,那就更好了,因此您可以使用 size()
Also it would be even better if you used ArrayList<String>
so you could use size()
ArrayList<String> arrayName = new ArrayList<String>(20);
System.out.println(arrayName.size());
由于未将任何元素添加到ArrayList,因此它将打印0.
It will print 0, as there are no elements added to the ArrayList.
这篇关于如何获取不为null的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!