Jak wstawić obiekt do ArrayList w określonej pozycji

Załóżmy, że mam Arraylistę obiektów o rozmiarze N. teraz chcę wstawić inny obiekt w określonej pozycji, powiedzmy w pozycji indeksu k (jest większy niż 0 i mniejszy niż n) i chcę, aby inne obiekty na i po pozycji indeksu k przesunęły jedną pozycję indeksu do przodu. Czy jest jakiś sposób, aby to zrobić bezpośrednio w Javie. W rzeczywistości chcę zachować listę sortowane podczas dodawania nowego obiektu.

Author: Bohemian, 2011-08-16

5 answers

Do Wstaw wartość do ArrayList przy określonym indeksie, użyj:

public void add(int index, E element)

Ta metoda przesunie kolejne elementy listy. ale nie możesz zagwarantować, że lista pozostanie posortowana, ponieważ nowy obiekt, który wstawisz, może znajdować się na niewłaściwej pozycji zgodnie z kolejnością sortowania.


Do zastąp element w podanej pozycji, Użyj:

public E set(int index, E element)

Metoda ta zastępuje element w podanej pozycji w lista z podanym element i zwraca element wcześniej w określonej pozycji.

 133
Author: CloudyMarble,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-15 06:32:37

Oto prosty przykład arraylist do wstawiania w określonym indeksie

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]
 53
Author: Jaldip Katre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-03 12:48:50

Właściwie sposób, aby to zrobić na konkretne pytanie jest arrayList.add(1,"INSERTED ELEMENT"); gdzie 1 jest pozycją

 1
Author: Sergio López,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-31 05:34:24

Zauważ, że gdy wstawiasz do listy na pozycji, to tak naprawdę wstawiasz na Pozycja dynamiczna w obrębie obecnych elementów listy. Zobacz tutaj:

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)
 1
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-31 14:13:08

Na przykład:

Chcę przenieść element z 23th do 1th (index == 0) w arrayList, więc umieścić 23th element do wartości temp i usuwając z listy, wstawić go do 1th w liście. Działa, ale nie wydajniej.

 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);
        }
    }
 0
Author: Armysir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-02 06:26:43