【问题标题】:Adding object to last element of arraylist将对象添加到arraylist的最后一个元素
【发布时间】:2020-12-05 06:43:24
【问题描述】:

我正在创建一个可调整大小的对象数组。下面是我的 add 函数,我在其中传递了我想添加到我的数组列表中的对象。

该功能有效,但是如果有人可以解释此代码 temp[theList.length] = toAdd;

我知道它将参数参数添加到新 Arraylist 的末尾。但是让我感到困惑的是我传递给temp[] 的索引。我不应该包括theList.length + 1 而不仅仅是theList.length吗?

public boolean add(Object toAdd) {
        
    if (toAdd != null) {
            
        Object[] temp = new Object[theList.length + 1];
            
        for (int i = 0; i < theList.length; i++) {
            temp[i] = theList[i];
        }
        temp[theList.length] = toAdd;
        theList = temp;
        return true;
    } else {
        System.out.println("Invalid type");
        return false;
    }
}

【问题讨论】:

  • 你知道数组索引是从0开始的吗?
  • 数组索引从零开始。这意味着最后一个索引是length - 1。由于您创建了长度为theList.length + 1temp,这意味着temp 的最后一个索引是theList.length
  • 顺便说一句,您应该使用 List 而不是数组,因为它们可以增长
  • @David 这段代码看起来像是学生练习,所以数组可能是要求的一部分。
  • @DavidBrossard 这个方法看起来像是自定义列表类的实现,用作教授数组操作的练习,而使用ArrayList 会破坏练习的目的。

标签: java arrays arraylist


【解决方案1】:

add方法说明

假设theList的大小是10。

他们创建了一个temp 数组,其大小为theList + 1,因此temp 的大小为11。 现在,除了最后一个元素tem[10] 之外,其他对象都添加到了temp

要添加最后一个元素,您可以使用以下两种方式中的任何一种:

temp[theList.length] //temp[10]

或者

temp[temp.length-1] //temp[10]

他们使用第一种方式添加toAdd 对象。

【讨论】:

    【解决方案2】:

    您可以使用标准方法Arrays.copyOf 立即创建具有新大小的输入数组的副本(在这种情况下,长度会增加):

    import java.util.Arrays;
    
    //...
    
    public boolean add(Object toAdd) {
            
        if (toAdd != null) {
            int oldLength = theList.length;
            theList = Arrays.copyOf(theList, oldLength + 1);
            theList[oldLength] = toAdd;
    
            return true;
        } else {
            System.out.println("Cannot add null object");
            return false;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多