0

I am trying out a easy to understand example about contravariance in Java and having a issue understanding. In the below example I have List<? super CarBill> list1 . My understanding is i should be able to add an object of any superclass of CarBill. By that logic i should be able to add objects of Bill class to it too right ? I get a compilation error.

package Generics;

import java.util.ArrayList;
import java.util.List;

public class VarianceTests {
    static class Bill{
        String vName;
        String type;
        Bill(String vName){
            this.vName=vName;
        }
        Bill(String vName,String type){
            this.vName=vName;
            this.type=type;
        }
    }

    static class CarBill extends Bill{
        String name;
        CarBill(String name)
        {
            super(name,"Car");
        }
    }

    static class Car<T extends Bill> {
        T car;
        Car(T car){
            this.car=car;
        }

        String getNameOfCar() {
            return car.vName;
        }
    }


public static void main(String args[]) {
    CarBill cBill = new CarBill("Baleno");
    Bill bill=new Bill("Whatever");
    Car car = new Car(bill); //cBill is valid too as Car accepts <? extends Bill>

    List<? super CarBill> list1 = new ArrayList<>();
    list1.add(cBill);
    list1.add(bill);
}

public void acceptListOfCars(List<? extends Bill> list1) {
    Bill b = list1.get(0); //Valid syntax

}

}
2

3 Answers 3

3

Your understanding is mistaken.

List<? super CarBill> means that the list can be a list of any super class of CarBill or CarBill itself. It could be List<Object>, it could be List<Bill>, it could even be List<CarBill>. Which one is it actually? We don't know.

Therefore, you can't add a Bill to a List<? super CarBill> because what if the list is actually a List<CarBill>? You can't add a Bill to a List<CarBill>.

In other words, you can only add CarBill or subclasses of CarBill into a List<? super CarBill>.

If your intention is to create a list that can store any type of Bill, you can create a List<Bill>.

This post might help as well.

2

Not quite.

Let's start with this code:

List<Integer> listOfInts = new ArrayList<Integer>();
List<Number> listOfNumbers = listOfInts;
listOfNumbers.add(5.5D); // a double
int i = listOfInts.get(0); // uhoh!

The above code won't in fact compile; the second line is an invalid assignment. Your line of thinking would say: But.. why? Number is a supertype of Integer, so, a list of integers is trivially also a list of numbers, no? but then the third line shows why this line of reasoning is incorrect. Java will NOT let you write the above code. What you CAN write is this: The same thing, but this time we tweak the second line:

List<Integer> listOfInts = new ArrayList<Integer>();
List<? extends Number> listOfNumbers = listOfInts;
listOfNumbers.add(5.5D); // a double
int i = listOfInts.get(0); // uhoh!

This time, you get a compiler error on the third line: You cannot add a double to this list. But, if you read from it, you'd get numbers out (not objects). This is all good: The above snippet of code should never compile no matter what we try because it tries to add doubles to a list of ints.

The point is: List<? extends Number> does not mean: "This list contains numbers, or any subtypes thereof". No; just like List x = new ArrayList() is legal java, List<Number> means 'this list contains numbers or any subtypes thereof' because any instance of any subtype of number can itself be used as a Number. List<? extends Number> means: This is a list restrained to contain only instances of some specific type, but which type is not known. What IS known, is that whatever that type is, it's either Number or some subtype thereof.

Hence, you can't add ANYTHING to a List<? extends Number>.

For super, a similar story:

List<? super CarBill> means: This is a list that is restricted to contain only instances of some specific type, but which type is not known. What IS known, is that, whatever type it is, it is either CarBill or some SUPERtype thereof.

The upside of doing this, is that you can add CarBill instances to a List<? super CarBill> variable. When you read from it, you'll get objects out.

1

My understanding is i should be able to add an object of any superclass of CarBill

No.

A List<? super CarBill> is not a list that will accept objects of any supertype of CarBill. It's a list that will accept objects of some particular supertype of CarBill, but which supertype it is is unknown.

You can add any object of type CarBill, because that is guaranteed be a subtype of type ?. But a supertype of CarBill is not guaranteed to be a subtype of ?.

For instance:

List<? super CarBill> myList = new ArrayList<Bill>();

Object o = "Anything";

Object is a supertype of CarBill. So if you could add any supertype of CarBill to the list, you would be able to add o to the list, which would mean you could add anything to the list.

5
  • so these covariant/contravariant notations seem to be mostly for "allowing to pass in values to methods restrictively " and in come cases return them. I guess what i m trying to get at is to find out when should i use them and why. Feb 18, 2019 at 9:27
  • 1
    List<? super CarBill> is the most abstract version of "a list that can accept instances of CarBill." In situations where you want a list that will (only) receive instances of CarBill, it is a suitable type to use.
    – khelwood
    Feb 18, 2019 at 9:28
  • It helps now. So , if now i have a function which accepts say List<? super CarBill> . I can pass a List<Bill> as well right. But when i add items to the list i can only add <CarBill> items to it ? Feb 18, 2019 at 15:03
  • 1
    Yes. You can pass a List<Bill> as a List<? super CarBill>. If you have a variable of type List<? super CarBill> you can only add to it items of type CarBill (or some subclass of CarBill).
    – khelwood
    Feb 18, 2019 at 15:06
  • ahh. Now the clouds are slowly clearing. Although i am seeing very limited scope of being able to use contravariance in real code though. Feb 18, 2019 at 15:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.