Home  >  Core Java

How to write generic method in java| Generic method Example

By Arvind Rai, October 31, 2013
Generic Methods is a method that takes input type of more than one class. Suppose we need to pass argument of different objects to same method. To makes it feasible we use Generic Methods. While declaring methods, we need to declare types. And then those types can be used as a class. Find the sample declaration of Generic Methods.
<T> void arrayToCollection(T[] arr, Collection<T> col) {
      for (T ob : arr) {
          col.add(ob);
      }
      System.out.println(col.size());
  }
 
In the above code snippet, generic type is T, it can be any alphabet. Now T has been declared as arguments types and being used in the code as an class and its object. Find the complete example below.

GenericMethodDemo.java
package com.concretepage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class GenericMethodDemo {
  public static void main(String[] args) throws IOException {
    Person p1 = new Person("Ram",22);
    Person p2 = new Person("Shyam",21);
    List<Person> list = new ArrayList<Person>() ;
    Person[] parr = {p1,p2};
    GenericMethodDemo.arrayToCollection(parr, list);
  }
  static <T> void arrayToCollection(T[] arr, Collection<T> col) {
      for (T ob : arr) {
          col.add(ob);
      }
      System.out.println(col.size());
  }
}

class Person {
    private String name;
    private int age;
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
 
Generic Type can more than one. It can be as
<A,B,C,D> void add(A a, B b, C c, D d){}
 
Generic type has nothing to do with return type. Generic type helps the coder to write a code with minimum code of lines and efficient for maintenance.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us