【问题标题】:removing the right most elements in ArrayList删除 ArrayList 中最右边的元素
【发布时间】:2015-12-28 20:42:44
【问题描述】:

我想删除列表的最右半部分,但此代码有时可以,有时则不行。

如果 l 包含A → B → C → D → E,那么在调用之后 l.removeRightmostHalf(),l 变为 A → B → C

public void removeRightmostHalf() {
  if (size % 2 != 0)
  {
    current = (size / 2) + 1;
    while(current <= size)
    {
      for (int i = current + 1; i < size; i++)
         nodes[i-1] = nodes[i];
      size--;
      if (size == 0)
        current = -1;
      else if (current == size)
        current = 0;
    }
  }
  else 
  {
    current = (size / 2);
    while(current <= size)
    {
      for (int i = current + 1; i < size; i++)
        nodes[i-1] = nodes[i];
      size--;
      if (size == 0)
        current = -1;
      else if (current == size)
        current = 0;
    }
  }
}

【问题讨论】:

    标签: java arrays methods removeall


    【解决方案1】:

    此代码将完成工作尝试并告诉我。 如果我的回答对您来说是正确的,请不要忘记将其选为正确答案。

    public void removeRightmostHalf() {
        if (size % 2 != 0) 
            size=(size / 2)+1;
    
        else size=(size / 2);   
    }
    

    这是怎么做的? 因为问题是删除右半部分,从而将大小减小到一半,这将使数组的右部分无法访问,就像 Arraylist.Remove() 所做的那样。

    【讨论】:

    • @geoffrey 因为她从 remove() 方法中复制了很多东西,而且在这个地方没有任何意义,她也没有问为什么/什么
    • @geoffrey 去提交你的答案,没人管你
    • @geoffrey 如果数组列表包含 A,B,C,D,E ,您的方法将使其成为 A,B 您确实删除了最后 3 个元素这不是她解释的内容例如,如果元素像 5 一样奇数,则删除最后 2 个
    • @geoffrey 我在 Eclipse 上测试了很多次,它没有达到她的要求
    • @geoffrey 您确实多次编辑了您的答案,但仍然无法正常工作,在最后一个答案中它显示了所有元素
    【解决方案2】:
    public void removeRightmostHalf() 
    {
        if (size % 2 != 0)
           current = (size / 2) + 1;
        else
           current=size/2;
        nodes.subList(current,size).clear()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 2016-07-23
      • 1970-01-01
      • 2018-04-07
      • 2022-11-18
      • 2014-08-28
      相关资源
      最近更新 更多