Skip to content

Instantly share code, notes, and snippets.

@codinko
Created October 8, 2015 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinko/1a1080c4dac71a87623b to your computer and use it in GitHub Desktop.
Save codinko/1a1080c4dac71a87623b to your computer and use it in GitHub Desktop.
Java Generics – Part5 – Generic methods - Sample Program
package com.codinko.generics;
public class GenericClass<T> {
private T t;
public T get() {
return this.t;
}
public void set(T t) {
this.t = t;
}
}
package com.codinko.generics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class GenericMethod1 {
// with wild card '?' this is not possible.
// public static <?> addTooCollectionAndReturnElement(<?> element,
// Collection<?> collection)// INVALID
public <T> T addToCollectionAndReturnElement(T element, Collection<T> collection) {
collection.add(element);
return element;
}
// static method
public static <T> T addToCollectionAndReturnElement2(T element, Collection<T> collection) {
collection.add(element);
return element;
}
public static void main(String[] args) {
String name = "Harley";
List<String> nameList = new ArrayList<String>();
String nameElement = new GenericMethod1().<String> addToCollectionAndReturnElement(name, nameList);
// We really don't need to specify the <String> type of teh generic method.
//Compiler infer it. It's called type inference
nameElement = new GenericMethod1().addToCollectionAndReturnElement(name, nameList);
System.out.println(nameElement);
Integer age = new Integer(25);
List<Integer> ageList = new ArrayList<Integer>();
Integer ageElement = addToCollectionAndReturnElement2(age, ageList);
System.out.println(ageElement);
}
}
package com.codinko.generics;
public class GenericMethod2 {
//Generic Method
public static <T> boolean isEqual(GenericClass<T> g1, GenericClass<T> g2) {
return g1.get().equals(g2.get());
}
public static void main(String args[]) {
GenericClass<String> obj1 = new GenericClass<String>();
obj1.set("Harley");
GenericClass<String> obj2 = new GenericClass<String>();
obj2.set("Harley");
boolean isEqual = GenericMethod2.<String> isEqual(obj1, obj2);
isEqual = GenericMethod2.isEqual(obj1, obj2);
System.out.println(isEqual);
// This feature is called type inference. It allows you to invoke a
// generic method as an
// ordinary method, without specifying a type between angle brackets.
// Compiler will infer the type that is needed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment