3 ms·
We had to learn it when doing an oo programming course at university. And I immediately forgot all about it. I hope when writing Java code sometimes at a job,
by myspy 15y ago
We had to learn it when doing an oo programming course at university. And I immediately forgot all about it.
I hope when writing Java code sometimes at a job, I can refer to this again.
This is all done in the name of type safe programming (I don't know the exact english terminology).
<? extends B> is called covariance. It helps to access attributes of B and derived classes with get() but prevents to use set().
ArrayList<? extends Number> list;
list = new ArrayList<Integer>();
list = new ArrayList<Double>();
list = new ArrayList<Long>();
list.set(index, myInteger); // throws error
Compiler has to know the exact type to set the value, but Long, Double and Integer are all from type Number, so you can read it into a Number variable.
Is that correct?
- guard-of-terra 15y agoYou describe how it works, but not what it means in simple terms. List<Shape> is not a "list of Shapes", it's a "list parametrized with Shape" List<? extends Shape> is a "list parametrized with something that extends Shape" e.g. you can assign it with List<Circle> (you can't assign it to List<Shape> since Shape != Circle) and then you can do operations on it that would not break List<Circle> (can't put Square in it)
- myspy 15y agoGreat, thank you. It's interesting to learn, when you don't know how to describe something in simple terms. I blame my lacking college professor and me, not taking enough time to learn it properly.