Generic Methods

Generics can be applied at method level. Generic methods are really helpful when there are some collections operation has to be performed e.g. delete, add, update etc…

public void add(T obj, List list){
    ...
    list.add(obj);
    ... 
}

public T getData(int index){
   this.list.get(index);
}

To be able to create Generic methods, you must need to define Generic types at Class level. Below example will give you clear picture of generic methods

class Group {
	List group;
	
	public Group() {
		group = new ArrayList();
	}
	public E get(int index){
		return this.group.get(index);
	}
	
	public void add(E e){
		this.group.add(e);
	}
}

class Friends{
...
}

class Colleagues{
...
}

public static void main(String[] args) {
	Group friendsGroup = new Group();
	friendsGroup.add(new Friends());
	Friends emp = friendsGroup.get(0);
	System.out.println(emp);
}

Generic methods are usually implemented where there is a collection handing objects (CRUD) within the class. You won’t be able to invoke any instance method from Generic type ‘T t’.

One comment

  1. Kelli

    An answer from an expert! Thanks for coiittburnng.

Leave a Reply

Your email address will not be published. Required fields are marked *