지정된 인덱스에서 ArrayList에 객체 추가 list = new ArrayList<object>(); 추가하려는 객체가 있으며

나는 그것이 매우 간단한 질문이라고 생각하지만, 이것을 올바르게 수행하는 방법을 알 수는 없습니다.

빈 배열 목록이 있습니다.

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

추가하려는 객체가 있으며 각 객체는 특정 위치에 있어야합니다. 그러나 가능한 각 순서대로 추가 할 수 있어야합니다. 이것을 시도하면 작동하지 않으며 IndexOutOfBoundsException:

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

내가 시도하면 충전입니다 ArrayList함께 null다음 위의 일입니다. 작동하지만 끔찍한 해결책이라고 생각합니다. 다른 방법이 있습니까?



답변

다음과 같이 할 수 있습니다 :

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

object2를 위치 2에 추가하면 object3이 위치 3으로 이동합니다.

항상 object3을 position3에 배치하려면 위치를 키로, 객체를 값으로 사용하여 HashMap을 사용하는 것이 좋습니다.


답변

객체 배열을 사용하여 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]


답변

그렇다면 일반 Array 사용을 고려하지 않는 것이 좋습니다. 용량을 초기화하고 원하는 인덱스에 객체를 넣으십시오.

Object[] list = new Object[10];

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


답변

크기와 추가하려는 요소 사이에 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의 어느 시점 에나 추가 할 수 있습니다. 예를 들어이 주요 방법은 다음과 같습니다.

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 : 영

1 : 하나

2 : 두

3 : null

4 : 널

5 : 5


답변

나는 당신의 관심을 끌기 ArrayList.add문서 가 발생 말한다 IndexOutOfBoundsException– 인덱스가 범위 외의 경우 ( index < 0 || index > size())

size()전화하기 전에 목록을 확인하십시오list.add(1, object1)


답변

빈 인덱스를 null로 채워야합니다.

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

arraylist.add(position, object);


답변

@Maethortje

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

지정된 위치에 요소를 추가하려고하면 IndexOutOfBound가 생겼으므로 목록에 해당 위치에 일부 요소가 있어야합니다.

다음을 시도하십시오

/*
  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

*/