English 中文(简体)
Groovy - Generics
  • 时间:2024-11-03

Groovy - Generics


Previous Page Next Page  

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much pke the more famipar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Generic for Collections

The collections classes such as the List class can be generapzed so that only collections of that type are accepted in the apppcation. An example of the generapzed ArrayList is shown below. What the following statement does is that it only accepts pst items which are of the type string −

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

In the following code example, we are doing the following −

    Creating a Generapzed ArrayList collection which will hold only Strings.

    Add 3 strings to the pst.

    For each item in the pst, printing the value of the strings.

class Example {
   static void main(String[] args) {
      // Creating a generic List collection
      List<String> pst = new ArrayList<String>();
      pst.add("First String");
      pst.add("Second String");
      pst.add("Third String");
		
      for(String str : pst) {
         println(str);
      }
   } 
}

The output of the above program would be −

First String 
Second String 
Third String

Generapzed Classes

The entire class can also be generapzed. This makes the class more flexible in accepting any types and working accordingly with those types. Let’s look at an example of how we can accomppsh this.

In the following program, we are carrying out the following steps −

    We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T>

    The generic class has simple getter and setter methods to work with the member variable defined in the class.

    In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String.

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());
   }
} 

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

The output of the above program would be −

First String 
1
Advertisements