Tuesday 11 March 2014

Generic Methods

Just like Generic classes and generic Interfaces, Java supports Generic Methods.

The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type.

Syntax
<T1, T2, …..TN> returnType methodName(parameters);

class KeyValue<K, V>{
 private K key;
 private V value;

 // Generic constructor
 KeyValue(K key, V value) {
  this.key = key;
  this.value = value;
 }

 // Generic methods
 public void setKey(K key) { this.key = key; }
 public void setValue(V value) { this.value = value; }
 public K getKey() { return key; }
 public V getValue() { return value; }
}

class GenericMethod{
 <K,V> boolean compare(KeyValue<K, V> key1, KeyValue<K, V> key2){
  return key1.getKey().equals(key2.getKey()) &&
     key1.getValue().equals(key2.getValue());
 }

 public static void main(String args[]){
  KeyValue<Integer, String> key1 = new KeyValue<> (1, "ABCD");
  KeyValue<Integer, String> key2 = new KeyValue<> (1, "ABCD");
  KeyValue<Integer, String> key3 = new KeyValue<> (2, "EFGH");

  GenericMethod obj = new GenericMethod();

  System.out.print("Is keys key1 and key2 are equal ");
  System.out.println(obj.compare(key1, key2));
  System.out.print("Is keys key1 and key3 are equal ");
  System.out.println(obj.compare(key1, key3));
 }
}
   
Output
Is keys key1 and key2 are equal true
Is keys key1 and key3 are equal false
    
<K,V> boolean compare(KeyValue<K, V> key1, KeyValue<K, V> key2) is a Generic Method.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment