英文:
Exceed capacity
问题
以下是您要翻译的代码部分:
让我们假设我们有一个简单的ArrayList/Vector实现,这是在超出容量时调用的分配函数
private void allocateCapacity(int capacity)
{
// private Object [] m_elems;
Object [] tmp = Arrays.copyOf(m_elems, capacity);
Arrays.fill(m_elems, null); // 这个地方让我困惑,我是否应该写这一行或不写?
m_elems = tmp;
}
英文:
Let's say we have simple ArrayList/Vector implementation, Here is my alloc function when we exceeded capacity
private void allocateCapacity(int capacity)
{
// private Object [] m_elems;
Object [] tmp = Arrays.copyOf(m_elems, capacity);
Arrays.fill(m_elems, null); // this point where I confused, Should I have to write this line or not?
m_elems = tmp;
}
答案1
得分: 0
Arrays.copyOf(m_elems, capacity);
将会创建一个大小为 capacity 的 m_elements 副本。我将在这里引用 javadoc:
> 复制指定的数组,如果需要,截断或填充为 null,以使副本具有指定的长度。
这意味着如果 capacity 大于原始数组,您的数组将已经填充了 null。
我可能会写成一行代码:
m_elems = Arrays.copyOf(m_elems, capacity);
英文:
Arrays.copyOf(m_elems, capacity);
Will create a copy of the m_elements with size capacity. And I will reference the javadoc here:
> Copies the specified array, truncating or padding with nulls (if
> necessary) so the copy has the specified length.
Which means your array will already be padded with nulls if capacity is bigger than your original array.
I would have probably written a one liner:
m_elems = Arrays.copyOf(m_elems, capacity);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论