When is a parameterized method call useful?

梦想的初衷 提交于 2019-12-03 23:15:21

I never have used this in practice, but you can imagine to use this for type safety. Consider the following method:

<T> void method(T... items) {
    List<T> list = new ArrayList<T>();
    for (T item : items)
        list.add(item);
    System.out.println(list);
}

You can call it this way:

o.<Object>method("Blah", new Long(0));
o.<Number>method(new Integer(100), new Long(0));

But this will raise an compiler error:

o.<Number>method("String", new Long(0));

So you have an generic method that is typesafe and can be used for every Object, not limited to a paricular interface or class.

Parameterized method calls are useful when you want to allow different types without casting. For example, the Collections helper class makes extensive use of parameterized method calls. When you want to make a new generic collection using one of their helper methods, a few examples:

List<String> anEmptyStringList = Collections.<String>emptyList();
Set<Integer> unmodifiableCopy = Collections.<Integer>unmodifiableSet(originalSet);

So, when you want to be able to use the generic type elsewhere, you want to use those method calls. They prevent compiler warnings when using generics.

It is probably most useful when you are taking a collection of some type, and returning some subset of that collection.

<T> List<T> filter(Collection<? extends T> coll, Predicate<? super T> pred) {
    List<T> returnList = new ArrayList<T>();
    for(T t : coll) {
        if(pred.matches(t)){
            returnList.add(t);
        }
    }
    return returnList;
}

Edit:

More generally, it is useful whenever you wish to return a specific type, or you want to link the types of two or more parameters in a general way.

For example, when you need some universal method for comparisons:

public static <T extends Comparable> T max(T one, T two) {
    if (one.compareTo(two) > 0) {
        return one;
    } else {
        return two;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!