Q:

Integer List Example (Create, Add elements, Remove and print) in Java

belongs to collection: Java List Programs

0

What is list?

List in an interface, which is implemented by the ArrayList, LinkedList, Vector and Stack. It is an ordered collection of the object, where duplicate objects can also be stored.

In this example, we are performing following operations:

  • Creating a list of integers - implemented by ArrayList
  • Printing the empty List
  • Adding elements to the List and printing
  • Adding elements to the List at given indexes and printing
  • Removing elements from the List by index and printing

Following methods are using in the program:

  • List.add(element) - Adds element at the end of the List
  • List.add(index, element) - Inserts element at given index
  • List.remove(index) - Removes the element from given index
  •  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example:

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    //creating a list of integers
    List < Integer > list = new ArrayList < Integer > ();

    //printing the list
    System.out.print("list= ");
    System.out.println(list);

    //adding elements
    list.add(10);
    list.add(20);
    list.add(30);
    list.add(40);
    list.add(50);

    //printing the list 
    System.out.print("list= ");
    System.out.println(list);

    //adding elements by specifying Iindex
    list.add(0, 5); //will add 5 at 0th Index
    list.add(3, 7); //will add 7 at 3th index 

    //printing the list 
    System.out.print("list= ");
    System.out.println(list);

    //removeing elements
    list.remove(0); //wili remove element from index 0
    list.remove(3); //will remove element from index 3

    //printing the list 
    System.out.println("list= ");
    System.out.println(list);
  }
};

Output

list= []
list= [10, 20, 30, 40, 50]
list= [5, 10, 20, 7, 30, 40, 50]
list=
[10, 20, 7, 40, 50]

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Add object/element to the List at specified index ... >>