如何在 ArrayList 中的特定位置插入对象 [英] How to insert an object in an ArrayList at a specific position

查看:27
本文介绍了如何在 ArrayList 中的特定位置插入对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个大小为 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.

推荐答案

要将值插入到ArrayList的特定索引处,使用:

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

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

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.

这篇关于如何在 ArrayList 中的特定位置插入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆