如何在ArrayList中的特定位置插入对象

发布于 11-30 04:14 字数 151 浏览 0 评论 0原文

假设我有一个大小为 n 的对象的 ArrayList。现在我想在特定位置插入另一个对象,假设在索引位置 k (大于 0 且小于 n),并且我希望索引位置 k 处及其之后的其他对象向前移动一个索引位置。那么有没有什么方法可以直接在Java中做到这一点。实际上我想在添加新对象时保持列表排序。

Suppose I have an ArrayList of objects of size n. Now I want to insert an another object at specific position, let's say at index position k (is greater than 0 and less than n) and I want other objects at and after index position k to shift one index position ahead. So is there any way to do this directly in Java. Actually i want to keep the list sorted while adding new object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

弥枳2024-12-07 04:14:47

要在特定索引处插入值到 ArrayList 中,请使用:

public void add(int index, E element)

此方法将移动列表的后续元素。但您不能保证列表将保持排序,因为您插入的新对象可能根据排序顺序位于错误的位置。


替换指定位置的元素,请使用:

public E set(int index, E element)

此方法替换指定位置的元素
列出指定元素,并返回之前的元素
在指定位置。

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)

This method replaces the element at the specified position in the
list with the specified element, and returns the element previously
at the specified position.

抹茶夏天i‖2024-12-07 04:14:47

这是在特定索引处插入的简单数组列表示例

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]

Here is the simple arraylist example for insertion at specific index

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]
孤云独去闲2024-12-07 04:14:47

来自 Oracle 官方文档

此方法将指定的元素追加到此列表的末尾。

add(E e) //append element to the end of the arraylist.

此方法在指定的位置插入指定的元素在此列表中的位置。

void add(int index, E element) //inserts element at the given position in the array list.

此方法将此列表中指定位置的元素替换为指定元素。

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

From Oracle Official Documentation

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      
天荒地未老2024-12-07 04:14:47

请注意,当您在列表中的某个位置插入时,您实际上是在列表当前元素内的动态位置插入。请参阅此处:

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

线程“main”中的异常 java.lang.IndexOutOfBoundsException:索引:15,大小:0
    在 java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
    在 java.util.ArrayList.add(ArrayList.java:473)
    在 com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:

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)
冷弦2024-12-07 04:14:47

实际上,针对您的具体问题执行此操作的方法是 arrayList.add(1,"INSERTED ELEMENT"); 其中 1 是位置

Actually the way to do it on your specific question is arrayList.add(1,"INSERTED ELEMENT"); where 1 is the position

半寸时光2024-12-07 04:14:47

添加到某个位置时必须自己处理ArrayIndexOutOfBounds。

为了方便起见,你可以在 Kotlin 中使用这个扩展函数

/**
 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
 */
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {
        add(element)
    }
}

You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.

For convenience, you may use this extension function in Kotlin

/**
 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
 */
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {
        add(element)
    }
}
清醇2024-12-07 04:14:47
ArrayList<Integer> someData = new ArrayList<Integer>();
someData.add(1);
someData.add(2);
someData.add(3);
someData.add(4);
someData.add(5);
// currently someData = {1, 2, 3, 4, 5}


// Using add method with position someData = {1, 2, 3, 4, 6, 5}. size of array is increased
someData.add(5,6);

// Using set method with position someData = {1, 2, 3, 4, 7, 5}. Size remains same
someData.set(5,7);

阅读更多详细信息 此处

ArrayList<Integer> someData = new ArrayList<Integer>();
someData.add(1);
someData.add(2);
someData.add(3);
someData.add(4);
someData.add(5);
// currently someData = {1, 2, 3, 4, 5}


// Using add method with position someData = {1, 2, 3, 4, 6, 5}. size of array is increased
someData.add(5,6);

// Using set method with position someData = {1, 2, 3, 4, 7, 5}. Size remains same
someData.set(5,7);

Read in more detail here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文