Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java What is difference between generic method and a method object as a parameter?

Tags:

java

generics

What are advantage between a generic method and a method just accepts Object? How does it ensures type safety?

For example: What difference does it make when define my interface in either of the form mentioned in below code snippet?

public interface MyInterface {
  public <MT> String myMethod(MT t);
}

OR

public interface MyInterface {
  public String myMethod(Object t);
}

In my opinion Generic methods are advantageous only when we type bound around it.. for example type parameter should of Serializable class like. Otherwise it doesn't make sense.. looking for more insight

public interface MyInterface {
  public <MT extends Serializable> String myMethod(MT t);
}
like image 308
Chetan Avatar asked Dec 21 '12 19:12

Chetan


1 Answers

A method is usually made generic to ensure that two arguments are compatible with each other, or to return a value whose type depends on the generic type of the method.

For example,

public static <T> void sort(List<T> list, Comparator<? super T> c)

makes sure the type of the list and the type of the comparator are compatible, which wouldn't necessary be the same if the signature was

public static void sort(List list, Comparator c)

In the following example, the returned value's type depends on the generic type of the method:

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

which allows doing:

List<Integer> intList = ...;
Integer min = Collections.min(intList);

If the method was

public static Comparable T min(Collection coll)

you would have to do

Integer min = (Integer) Collections.min(intList);

and you wouldn't have any warning from the compiler if you changed the code to

Long min = (Long) Collections.min(intList);
like image 159
JB Nizet Avatar answered Nov 09 '22 09:11

JB Nizet