Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics:Issues in Adding SubClass Objects in a Collection

Tags:

java

generics

So I've been reading through the Generics tutorial offered by Oracle here: http://docs.oracle.com/javase/tutorial/java/generics/

And I've tried running my own example to make sure I understand how to use Generics. I have the following code:

import java.util.*;

public class Generics {
    class NaturalNumber {
        private int i;

        public NaturalNumber(int i) { this.i = i; }
    }
    class EvenNumber extends NaturalNumber {
        public EvenNumber(int i) { 
            super(i);
        }
    }    
    public static void main(String[] args) {
        Collection<? extends NaturalNumber> c = new ArrayList<>();
        c.add(new EvenNumber(2)); //this line produces a compile time error     
    }
}

My goal is to be able to add any object which is a subtype of NaturalNumber to the Collection c. I'm not sure why this doesn't work and reading through Oracle's tutorial hasn't enlightened me either.

like image 795
ajavad Avatar asked Feb 16 '23 12:02

ajavad


1 Answers

When you have ? extends NaturalNumber, the parameter could be some other subclass of NaturalNumber that is in no way related to EvenNumber. For instance,

Collection<? extends NaturalNumber> c = new ArrayList<OtherNaturalNumber>();

is valid if OtherNaturalNumber extends NaturalNumber.

Consequently, you are not able to add an EvenNumber instance to the list. You can just use this declaration:

Collection<NaturalNumber> c = new ArrayList<>();

which will allow you to add any NaturalNumber instance (including an EvenNumber).

On another note, you probably meant to make those nested classes static (or don't nest them at all).

like image 111
arshajii Avatar answered Feb 20 '23 09:02

arshajii