gpt4 book ai didi

java - 如何查看数组中有多少内存位置已满

转载 作者:行者123 更新时间:2023-11-29 07:58:19 26 4
gpt4 key购买 nike

我正在做的一个项目需要帮助。所以我分配了我的数组,例如:

hand = new PlayingCard[5]; //5 Cards in a hand

我为 hand[0]hand[1] 设置了信息,

hand[0] = deck.dealACard(); 
hand[1] = newDeck.dealACard();

我的问题是,当我试图弄清楚有多少目前手上有牌[ ] 我得到“5”而不是“2”。

numCards = hand.length;

我现在需要做什么才能使 numCards 等于“2”?

最佳答案

你可以很容易地使用:

public static int countNonNullElements(Object[] array) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
count++;
}
}
return count;
}

但是,通常使用 List<E> 会更好相反(例如 ArrayList<E> )来表示具有不同大小的集合。

关于java - 如何查看数组中有多少内存位置已满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16147429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com