Insert Elements In ArrayList At Specific Position | Java Programs

Output:

*** Insert Elements In ArrayList At Specific Position ***

[Audi, BMW, Bigatti, Ferrari, Honda]

Inserting "Toyota" at first position and
"Lamborghini" at 4th position

[Toyota, Audi, BMW, Lamborghini, Bigatti, Ferrari, Honda]

Click Here For Java Online Compiler

Solution:

/**
 *
 * @author Alee Ahmed Kolachi
 */
import java.util.ArrayList;

public class InsertElementAtPositionFirst {

    public static void main(String[] args) {
        // Creae a list and add some elements to the list
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("Audi");
        arrayList.add("BMW");
        arrayList.add("Bigatti");
        arrayList.add("Ferrari");
        arrayList.add("Honda");

        System.out.println("*** Insert Elements In ArrayList At Specific Position ***" + "\n");
        System.out.println(arrayList);
        // Now insert an element at the first and 4rd position of the list
        System.out.println("\nInserting \"Toyota\" at first position and");
        System.out.println("\"Lamborghini\" at 4th position");
        System.out.println();
        arrayList.add(0, "Toyota");
        arrayList.add(3, "Lamborghini");

        System.out.println(arrayList);
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon