Thursday, July 28, 2016

Why generics of type are used?


Lets have these classes:

public class SuperClass {
   // some methods

public class SubClass extends SuperClass{
   // some methods

So we are allowed to do this conversion:

SuperClass x = new SupClass();


But, we are not allowed to make such conversion:

List <SubClass> listSubs = ...
List <SuperClass> listSupers = listSubs; // compile time error happens

Such a stupid language limitation! In this case, there is no clean solution. The bad solutions produce new List and reinserts all elements into it.


But we could use "? extends Generics" structure in this way:

List <SubClass> listSubs = ...
List <? extends SuperClass> listSupers = listSubs; // NO errors

Note: It is normal that ? extends Class structure allows only supclasses of the generics to be used. I was glad to understand that you could use the generics type itself there. So it is also possible:

List <? extends SuperClass> listSupers = new LinkedList(); // NO errors

Error: "class or interface without bounds" solved

    public List<? extends SuperClass> getObjects() {
        List<? extends SuperClass> result = new ArrayList<? extends SuperClass>(1); // error: "class or interface without bounds"
        result.add( theNeededObject ); // error: "not suitable method found for ..."
        return result;

Fixed error:
    public List<? extends SuperClass> getObjects() {
        List<SuperClass> result = new ArrayList<>(1);
        result.add( theNeededObject );
        return result; // it is automatically converted from <SuperClass> to "<? extends SuperClass>"

No comments:

Post a Comment