Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách chèn đối tượng vào ArrayList tại vị trí cụ thể trong Java


Phương thức add() của ArrayList giúp thêm phần tử. Có 2 biến thể:

  • add(E e) − Thêm object vào cuối list.

  • public void add(int index, E element) − Thêm element tại vị trí index, dịch các phần tử hiện tại sang phải (tăng index lên 1).

Dùng add(index, element) để chèn tại vị trí yêu cầu.

Ví dụ

import java.util.ArrayList; import java.util.Iterator; public class OccurenceOfElements {    public static void main(String args[]) {       ArrayList <String> list = new ArrayList<String>();       //Instantiating an ArrayList object       list.add("JavaFX");       list.add("Java");       list.add("WebGL");       list.add("OpenCV");       list.add("OpenNLP");       list.add("JOGL");       list.add("Hadoop");       list.add("HBase");       list.add("Flume");       list.add("Mahout");       list.add("Impala");       System.out.println("Contents of the array list (first to last): ");       Iterator<String> it = list.iterator();       while(it.hasNext()) {          System.out.print(it.next()+", ");       }       //Adding elements at the 6th position:       list.add(6, "Hadoop");       it = list.iterator();       System.out.println();       System.out.println("Contents of the array list after inserting new element: ");       while(it.hasNext()) {          System.out.print(it.next()+" ");       }    } }

Kết quả

Contents of the array list (first to last): JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala, Contents of the array list after inserting new element: JavaFX Java WebGL OpenCV OpenNLP JOGL Hadoop Hadoop HBase Flume Mahout Impala