Reputation: 3030
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 -_-)
Upvotes: 1
Views: 520
Reputation: 2639
You can't add anythig to this list, because you don't know what type it really is.
Consider inheritance tree like this:
Number
|
|- BigInteger
|
|- NonNegativeInteger
|
|-PositiveInteger
You say that your list is list of elements which inherits from Number
. Ok, so suppose you want to add Number
to a list, but wait you could have List<BigInteger>
and you cannot put Number
into it.
Ok, so you could put BigInteger
, right? No! Because your list could be List<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 type SomeObject
. Nothing else is known.
So how to avoid the problem? Just remove the template.
List<Number>
And now you can put anything what inherites from Number
.
Or, what is even better in your case, change Double
to E
:
private <E extends Number> void AddOne(ArrayList<E> al, E num) {
al.add(num);
}
Upvotes: 3
Reputation: 76908
Your method makes no sense. You want to add a Double
to an ArrayList
that is defined as holding any class that extends Number
.
What happens if the array you pass in is ArrayList<Integer>
and you try and add your Double
to it?
If you're only interested in having an ArrayList
that holds things that are subclasses of Number
, you don't need generics in your method; simply use an ArrayList<Number>
Upvotes: 2
Reputation: 41135
You should change your add to:
private <E extends Number> void AddOne(ArrayList<E> al, E num) {
al.add(num);
}
and then in any concrete instance of your generic class, where E
resolves to a specific number class, you'll be able to add numbers of that type.
Upvotes: 2
Reputation: 680
I think that what you really want is:
private void AddOne(ArrayList<Number> al, Double num) {
al.add(num);
}
Otherwise you can't add anything to the List with adding the cast to E
Upvotes: 1
Reputation: 18116
Do you mean this?
private void AddOne(ArrayList<Number> al, Double num) {
al.add(num);
}
Upvotes: 1