Can we add list inside list in Java?

1. Java List add[]

This method is used to add elements to the list. There are two methods to add elements to the list.

  1. add[E e]: appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created.
  2. add[int index, E element]: inserts the element at the given index. The elements from the given index is shifted towards right of the list. The method throws IndexOutOfBoundsException if the given index is out of range.

Lets look at some examples of List add[] methods.

package com.journaldev.examples; import java.util.ArrayList; import java.util.List; public class ListAddExamples { public static void main[String[] args] { List vowels = new ArrayList[]; vowels.add["A"]; // [A] vowels.add["E"]; // [A, E] vowels.add["U"]; // [A, E, U] System.out.println[vowels]; // [A, E, U] vowels.add[2, "I"]; // [A, E, I, U] vowels.add[3, "O"]; // [A, E, I, O, U] System.out.println[vowels]; // [A, E, I, O, U] } }
Recommended Readings:
  • Java List
  • Java ArrayList

2. Java List addAll[]

This method is used to add the elements from a collection to the list. There are two overloaded addAll[] methods.

  1. addAll[Collection

Chủ Đề