Print Shortlink

Groovy/Java ArrayList code comparison

Given below is the code to create a simple ArrayList in Java and it’s equivalent in Groovy.

//Code in Java
ArrayList<String> countries = new ArrayList<String>();
countries.add("India");
countries.add("France");
countries.add("Spain");
System.out.println(countries.getClass().getName());//Prints java.util.ArrayList
for(int i=0;i<countries.size();i++){
	System.out.println(countries.get(i));
}

The Groovy equivalent of the same.

 
//Code in Groovy
countries = []
countries << "India"
countries << "Spain"
countries << "France"
println countries.class.name //Prints java.util.ArrayList
countries.each {println it}

Leave a Reply