Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Groovy generics


May 14, 2021 Groovy


Table of contents


Generic enable types (classes and interfaces) are used as parameters when defining classes, interfaces, and methods. b20> pe.

The universality of the collection

Collection classes, such as List classes, can be generalized so that only collections of that type are accepted in the application. The following is an example of generalizing ArayList. The effect of the following statement is that it only accepts list items of type string -

List<String> list = new ArrayList<String>();

In the following code example, we'll do the following:

  • Create a generic ArrayList collection that contains only strings.
  • Add three strings to the list.
  • For each item in the list, the value of the string is printed.
class Example {
   static void main(String[] args) {
      // Creating a generic List collection
      List<String> list = new ArrayList<String>();
      list.add("First String");
      list.add("Second String");
      list.add("Third String");
		
      for(String str : list) {
         println(str);
      }
   } 
}

The output of the above program will be -

First String 
Second String 
Third String

Generic class

The entire class can also be generalized. T his gives classes more flexibility to accept any type and work with those types accordingly. Let's look at an example of how we can do this.

In the following procedure, we follow these steps -

  • We're creating a class called ListType. N ote the keywords that are placed in front of the class definition. er. herefore, when we declare an object for this class, we can specify a type during the declaration, and the type will be in the placeholder.

  • Generic classes have simple getter and setter methods for handling member variables defined in classes.

  • In the main program, note that we can declare objects of the ListType class, but different types of objects. The first type is the Integer type, and the second type is the String type.

class Example {
   static void main(String[] args) {
      // Creating a generic List collection 
      ListType<String> lststr = new ListType<>();
      lststr.set("First String");
      println(lststr.get()); 
		
      ListType<Integer> lstint = new ListType<>();
      lstint.set(1);
      println(lstint.get());
   }
} 

public class ListType<T> {
   private T localt;
	
   public T get() {
      return this.localt;
   }
	
   public void set(T plocal) {
      this.localt = plocal;
   } 
}

The output of the above program will be -

First String 
1