超出容量

huangapple go评论80阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年4月6日 17:08:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61056355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定