I have the following method:
private <E extends Number> void AddOne(ArrayList<E> al, Double num) {
al.add(num);
}
al.add(num) doesn’t work. What is the best way I can insert a number into a generic Number Array?
So basically, I have a generic
ArrayList< E > al
And I want to insert a numeric value in it, how can I do this? (I remember C++ being a lot easier -_-)
You can’t add anythig to this list, because you don’t know what type it really is.
Consider inheritance tree like this:
You say that your list is list of elements which inherits from
Number. Ok, so suppose you want to addNumberto a list, but wait you could haveList<BigInteger>and you cannot putNumberinto it.Ok, so you could put
BigInteger, right? No! Because your list could beList<NonNegativeInteger>. And the story goes on and on…Declaring list as
List<T extends SomeObject>ensures you that when you get something from list it’s of typeSomeObject. Nothing else is known.So how to avoid the problem? Just remove the template.
And now you can put anything what inherites from
Number.Or, what is even better in your case, change
DoubletoE: