Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List add(Object value) method



Description

Groovy List add(Object value) method appends the new value to the end of this List.

Syntax

boolean add(Object value)

Parameters

value − Value to be appended to the list.

Return Value

Return Value − A Boolean value on whether the value was added.

Example - Adding Element to List of Integers

Following is an example of the usage of this method −

main.groovy

def lst = [11, 12, 13, 14];
		
println(lst);
lst.add(15);
println(lst);

Output

When we run the above program, we will get the following result −

[11, 12, 13, 14] 
[11, 12, 13, 14, 15] 

Example - Adding Element to List of Strings

Following is an example of the usage of this method −

main.groovy

def lst = [];
		
println(lst);
lst.add("Welcome");

println(lst);

Output

When we run the above program, we will get the following result −

[]
[Welcome]

Example - Adding Element to List of Objects

Following is an example of the usage of this method −

main.groovy

def lst = [];
		
lst.add(new Student(1, "Julie"));
lst.add(new Student(2, "Robert"));
println(lst)

class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

Output

When we run the above program, we will get the following result −

[[ 1, Julie ], [ 2, Robert ]]
groovy_lists.htm
Advertisements