Program Tip

특정 위치의 ArrayList에 개체를 삽입하는 방법

programtip 2020. 10. 20. 08:03
반응형

특정 위치의 ArrayList에 개체를 삽입하는 방법


n 크기의 객체로 구성된 ArrayList가 있다고 가정합니다. 이제 특정 위치에 다른 객체를 삽입하고 싶습니다. 즉, 인덱스 위치 k (0보다 크고 n보다 작음)에 있고 인덱스 위치 k와 그 이후의 다른 객체가 한 인덱스 위치 앞으로 이동하기를 원합니다. 따라서 Java에서 직접 수행 할 수있는 방법이 있습니다. 실제로 새 개체를 추가하는 동안 목록을 정렬하고 싶습니다.


특정 인덱스의 ArrayList에 값 삽입 하려면 다음을 사용하십시오.

public void add(int index, E element)

이 메서드는 목록의 후속 요소를 이동합니다. 그러나 삽입 한 새 개체가 정렬 순서에 따라 잘못된 위치에있을 수 있으므로 목록이 정렬 된 상태로 유지된다는 보장은 없습니다.


지정된 위치에서 요소 바꾸 려면 다음을 사용하십시오.

public E set(int index, E element)

이 메서드는 목록의 지정된 위치에있는 요소를 지정된 요소로 바꾸고 이전에 지정된 위치에있는 요소를 반환합니다.


다음은 특정 인덱스에 삽입하는 간단한 arraylist 예제입니다.

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

한 위치에서 List에 삽입하면 실제로 List의 현재 요소 내의 동적 위치에 삽입하는 것 입니다. 여기를 보아라:

http://tpcg.io/0KmArS

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list
      arrlist.add(15, 15);
      arrlist.add(22, 22);
      arrlist.add(30, 30);
      arrlist.add(40, 40);

      // adding element 25 at third position
      arrlist.add(2, 25);

      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
   }
}

$ javac com / tutorialspoint / ArrayListDemo.java

$ java -Xmx128M -Xms16M com / tutorialspoint / ArrayListDemo

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
    at java.util.ArrayList.add(ArrayList.java:473)
    at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

실제로 특정 질문에 대해 수행하는 방법은 arrayList.add(1,"INSERTED ELEMENT");1이 위치입니다.


예를 들면 :

arrayList에서 요소를 23 번째에서 1 번째 (index == 0)로 옮기고 싶으므로 23 번째 요소를 임시 값에 넣고 목록에서 제거하여 목록의 1 번째에 삽입합니다. 효과가 있었지만 더 효율적은 아닙니다.

 List<ItemBean> list = JSON.parseArray(channelJsonStr,ItemBean.class);
    for (int index = 0; index < list.size(); index++) {
        if (list.get(index).getId() == 23) { // id 23
            ItemBean bean = list.get(index);
            list.remove(index);
            list.add(0, bean);
        }
    }

참고URL : https://stackoverflow.com/questions/7074402/how-to-insert-an-object-in-an-arraylist-at-a-specific-position

반응형