簡體   English   中英

Java-以未知順序將元素添加到ArrayList

[英]Java - add element to ArrayList with unknown order

發現了有關ArrayList的一件有趣的事情,

ArrayList<String> list = new ArrayList<String>();
list.add(0, "0-element");
list.add(1, "1-element");
list.add(2, "2-element");

但是,如果元素不是以未知順序出現,例如。

ArrayList<String> list = new ArrayList<String>();
list.add(1, "1-element");  // IndexOutOfBoundsException
list.add(2, "2-element");
list.add(0, "0-element");

您會收到IndexOutOfBoundsException,這里唯一的選擇是使用Map而不是List?

或多或少,是的。 您不能在索引i處有元素但i-1處沒有List的狀態; 您不能在List當前不存在的索引處添加元素。

如果您閱讀javadoc ,則會顯示:

將指定的元素插入此列表中的指定位置。 將當前在該位置的元素(如果有)和任何后續元素右移(將其索引添加一個)。
拋出 IndexOutOfBoundsException-如果索引超出范圍(索引<0 ||索引> size())

因此,在您的第一個示例中,列表為空,並且元素插入到位置0(尚不存在,但第一個可用-索引= 0 <= size()= 0)。

在第二個示例中,您嘗試在位置1插入,但在位置0仍沒有插入,因此失敗(索引= 1> size()= 0)。

記錄在案

IndexOutOfBoundsException-如果索引超出范圍(索引<0 ||索引> size())

您可以在添加之前進行測試:

if (pos>=list.size()) list.add(element);
else list.add(pos, element);  

但是您所做的事情很奇怪(這就是為什么沒有方法進行測試和添加/插入的原因)。 您是否真的要在索引處添加(即,移動一些先前插入的元素)? 您確定不需要一個標准數組,從而允許您在任意索引處設置元素嗎?

只需檢查ArrayList中的add方法實現,即可得到答案

public void add(int index, E element) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);

    ensureCapacity(size+1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
    elementData[index] = element;
    size++;
}

快速使用

list.add("element1");
list.add("element2");
list.add("element3);

之所以得到那個IndexOutOfBoundsException,是因為您想訪問尚不存在的元素1。

從文檔ArrayList

Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

如果列表不包含重復項,並且您不關心順序,則可以使用Set<String>

首先,您應該使用ArrayList作為List

List<String> list = new ArrayList<String>();
list.add("...");

我認為您還應該使用Set而不是List

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM