将对象添加到指定索引处的 ArrayList

我认为这是一个相当简单的问题,但我不知道如何正确地做到这一点。

我得到了一个空数组列表:

ArrayList<object> list = new ArrayList<object>();

我有一些对象,我想在其中添加对象,每个对象必须在一个特定的位置。然而,有必要按照每种可能的顺序添加它们。当我尝试这个,它不工作,我得到一个 IndexOutOfBoundsException:

list.add(1, object1)
list.add(3, object3)
list.add(2, object2)

我所尝试的是用 null填充 ArrayList,然后执行上述操作。有用,但我觉得这是个糟糕的解决方案。还有别的办法吗?

394107 次浏览

你可以这样做:

list.add(1, object1)
list.add(2, object3)
list.add(2, object2)

将 object2添加到位置2后,它将把 object3移动到位置3。

如果您希望 object3始终处于 position 3,我建议您使用 HashMap,其中 position 作为键,object 作为值。

如果是这样的话,那么为什么不考虑使用常规 Array,初始化容量并将对象放在所需的索引位置。

Object[] list = new Object[10];


list[0] = object1;
list[2] = object3;
list[1] = object2;

我把你的注意力吸引到 ArrayList.add文档,它说它抛出 IndexOutOfBoundsException-如果索引超出范围(index < 0 || index > size())

在调用 list.add(1, object1)之前检查列表的 size()

@Maethortje


The problem here is java creates an empty list when you called new ArrayList and

当尝试在指定位置添加元素时, 所以列表的位置应该有一些元素。

请跟我来

/*
Add an element to specified index of Java ArrayList Example
This Java Example shows how to add an element at specified index of java
ArrayList object using add method.
*/


import java.util.ArrayList;


public class AddElementToSpecifiedIndexArrayListExample {


public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();


//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");


/*
To add an element at the specified index of ArrayList use
void add(int index, Object obj) method.
This method inserts the specified element at the specified index in the
ArrayList.
*/
arrayList.add(1,"INSERTED ELEMENT");


/*
Please note that add method DOES NOT overwrites the element previously
at the specified index in the list. It shifts the elements to right side
and increasing the list size by 1.
*/


System.out.println("ArrayList contains...");
//display elements of ArrayList
for(int index=0; index < arrayList.size(); index++)
System.out.println(arrayList.get(index));


}
}


/*
Output would be
ArrayList contains...
1
INSERTED ELEMENT
2
3


*/

我认为美多巴的解决方案就是你要找的。

但是另一种解决方案是使用 HashMap 并使用键(Integer)来存储位置。

这样你就不需要用空值等填充它,只需要在映射中保留位置和对象就可以了。如果需要,可以在末尾写几行代码将其转换为 List。

可以使用 Array of 对象并将其转换为 ArrayList-

Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";


List<Object> list= Arrays.asList(array);

ArrayList 将是-[1,null,2,3,null,null,null,7,null,null ]

还可以重写 ArrayList,在大小和要添加的元素之间插入空值。

import java.util.ArrayList;




public class ArrayListAnySize<E> extends ArrayList<E>{
@Override
public void add(int index, E element){
if(index >= 0 && index <= size()){
super.add(index, element);
return;
}
int insertNulls = index - size();
for(int i = 0; i < insertNulls; i++){
super.add(null);
}
super.add(element);
}
}

然后您可以在 ArrayList 中的任何位置添加,例如,这个 main 方法:

public static void main(String[] args){
ArrayListAnySize<String> a = new ArrayListAnySize<>();
a.add("zero");
a.add("one");
a.add("two");
a.add(5,"five");
for(int i = 0; i < a.size(); i++){
System.out.println(i+": "+a.get(i));
}
}

从控制台产生以下结果:

0:0

一比一

2:2

第3集: 无效

第4集: 无效

五点五分

这个小的 while循环作为解决方案怎么样?

private ArrayList<Object> list = new ArrayList<Object>();


private void addObject(int i, Object object) {
while(list.size() < i) {
list.add(list.size(), null);
}
list.add(i, object);
}
....


addObject(1, object1)
addObject(3, object3)
addObject(2, object2)

这是一个可能的解决方案:

list.add(list.size(), new Object());

您需要用空值填充空索引。

while (arraylist.size() < position)
{
arraylist.add(null);
}


arraylist.add(position, object);

如果您正在使用 Java 的 Android 风格,我建议您使用 SparseArray。它比 Map 更有效地将整数映射到对象,并且更容易迭代

虽然有点晚,但希望对某些人还是有用的。

ArrayList中的特定位置添加项的2个步骤

  1. 指向 ArrayList中特定索引的 add空项
  2. 然后 set的立场,并根据需要。

        list = new ArrayList();//Initialise the ArrayList
    for (Integer i = 0; i < mItems.size(); i++) {
    list.add(i, null); //"Add" all positions to null
    }
    // "Set" Items
    list.set(position, SomeObject);
    

This way you don't have redundant items in the ArrayList i.e. if you were to add items such as,

list = new ArrayList(mItems.size());
list.add(position, SomeObject);

这将仅仅在位置上覆盖现有的项目,将现有的项目向右移动一个-所以你有一个数组列表,其中的索引数量是原来的两倍。

您应该设置而不是添加以替换索引处的现有值。

list.add(1, object1)
list.add(2, object3)
list.set(2, object2)

列表将包含[ object1,object2]

假设您想在某个位置添加一个项,那么列表大小必须大于该位置。

add(2, item): 这个语法意味着,将位于第2位的旧项目移动到下一个索引,并将该项目添加到第2位。

如果在第二位置没有项目,那么这将不工作,它将抛出一个异常。

这意味着如果你想 的东西在 position 2,

您的 清单大小必须至少是 (2 + 1) =3,,所以项目可在 0,1,2 Position.

这样就可以确保位置2是安全访问的,没有例外。