Iza Marek
Iza Marek

Reputation: 251

What are the benefits of contravariance in JAVA

I'd like to ask what are the benefits of using contravariance in JAVA?

Assume that we have two methods:

public static <T> void f1(List<? super T> list, T item){     
        list.add(item);     
    }

public static <T> void f2(List<T> list, T item){     
        list.add(item);     
    }

and I call them in the main:

public static main(){     
        f1(new ArrayList<Shape>(), new Cube());
        f2(new ArrayList<Shape>(), new Cube());     
    }

What is the different? Contravariance seems to be even worse cause we can only "get" Object type, so why and when should we use it?

Upvotes: 0

Views: 80

Answers (0)

Related Questions