Generics Wild Cards

There could be various scenarios where user needs to perform one operation over all objects belongs to similar type. Following example shows the limitation of the scenario:

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);
	}
	
	public List getAll(){
		return group;
	}
}
class Relation{
	private String name;
	public Relation(String name){
		this.name = name;
	}
	public void sendInvitation(String event){
		System.out.println("Invitation is sent to "+name+" for the event on "+event);
	}
}

class Friend extends Relation{

	public Friend(String name) {
		super(name);
	}
	
}

class Colleague extends Relation{
	public Colleague(String name) {
		super(name);
	}
	
}

public static void main(String[] args) {
	Group friendsGroup = new Group();
	friendsGroup.add(new Friend("Ajit"));
	friendsGroup.add(new Friend("Raj"));
	friendsGroup.add(new Colleague("Mohit"));
	
        ...
}

Here user has two different groups where one is personal friends group and others is colleagues from office. Now he has to do two attempts to send invitation. Let’s assume there is an EventManager is got the job of sending invitation to the Groups. If we don’t use generics, then code will be written something like:

class EventManager {
	public static void sendInvite(List groups){
		for (Object object : groups) {
			if(object instanceof Relation){
			//Type-casting is required.
				Relation relation = (Relation) object;
				relation.sendInvitation("Diwali festival");
			}
		}
	}
}

Above code is simple code where first it has to check for the instance class if the object is instance of Relation class. After that it’s type-casting is required to be able to send invitation. Next code snippet shows how generics wild card character solves that issue.

‘?’ wildcard character is used to accept any Class’s instance which extends Relation class.

class EventManager {
	
	public static void sendInvite(Group groups){
		for (Relation relation : groups.getAll()) {
			relation.sendInvitation("Diwali festival");
		}
	}
}

public static void main(String[] args) {
	Group friendsGroup = new Group();
	friendsGroup.add(new Friend("Ajit"));
	friendsGroup.add(new Friend("Raj"));
	friendsGroup.add(new Colleague("Mohit"));
	
	EventManager.sendInvite(friendsGroup);
}

2 comments

  1. Makailah

    If I comtanicumed I could thank you enough for this, I’d be lying.

    1. Arun Sharma Post author

      Thanks Makailah..

Leave a Reply

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