问题描述
所以说我有一个大小为10的数组,索引范围从0到9.
我添加了一堆元素并停止在索引6处添加。所以对于array.length,我可以知道数组的大小是10,但是如何找到哪个索引包含最后一个值,之后是否为空?我想要做一个循环并在index == null处停止吗?
So let say I have an array of size 10 with index range from 0 to 9.I add a bunch of elements in and stop adding at index 6. So with array.length, I can know that the size of the array is 10, but how do I find which index contain the last value and after that is empty? Am I suppose to do a loop and stop at index == null?
我通过创建一个动态数组来模仿一个arraylist,该数组在大小已满时会增长。
I mimic an arraylist by create a dynamic array that grow when the size is full.
Arg,忘了告诉你们,如果数组是int,那么空槽将是0?
Arg, forgot to tell you guys, if the array is int, then the empty slots will be 0?
推荐答案
使用 java.util.ArrayList
。在那里你不需要考虑索引,它是可调整大小的数组实现。
Use java.util.ArrayList
. There you no need to think about index and it is resizable-array implementation.
默认情况下,在创建数组时,所有值都为null,所以如果你不插入任何值在任何索引处的值(可能在数组的结尾或开始或中间)它将只是null。所以你应该把null检查来验证。
At the time of array creation by default all values are null so if you do not insert any value at any index (may be at end or beginning or middle of array) it would be just null. So you should put null check to verify.
这篇关于Java在数组索引中找到最后一个成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!