超出容量

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

Exceed capacity

问题

以下是您要翻译的代码部分:

  1. 让我们假设我们有一个简单的ArrayList/Vector实现这是在超出容量时调用的分配函数
  2. private void allocateCapacity(int capacity)
  3. {
  4. // private Object [] m_elems;
  5. Object [] tmp = Arrays.copyOf(m_elems, capacity);
  6. Arrays.fill(m_elems, null); // 这个地方让我困惑,我是否应该写这一行或不写?
  7. m_elems = tmp;
  8. }
英文:

Let's say we have simple ArrayList/Vector implementation, Here is my alloc function when we exceeded capacity

  1. private void allocateCapacity(int capacity)
  2. {
  3. // private Object [] m_elems;
  4. Object [] tmp = Arrays.copyOf(m_elems, capacity);
  5. Arrays.fill(m_elems, null); // this point where I confused, Should I have to write this line or not?
  6. m_elems = tmp;
  7. }

答案1

得分: 0

  1. Arrays.copyOf(m_elems, capacity);
  2. 将会创建一个大小为 capacity m_elements 副本。我将在这里引用 javadoc
  3. > 复制指定的数组,如果需要,截断或填充为 null,以使副本具有指定的长度。
  4. 这意味着如果 capacity 大于原始数组,您的数组将已经填充了 null
  5. 我可能会写成一行代码:
  6. m_elems = Arrays.copyOf(m_elems, capacity);
英文:
  1. 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:

  1. 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:

确定