Hi!
I am trying to create a collection of numbers -- that is a list (i.e. an arrayList) that contains both Integers and Doubles. The idea is I don't know whether each element is a Double or an Integer. I determine the raw type value per element by passing it to an overloaded method getVal() which returns either an int from Integer.intValue() or a double from Double.doubleValue().
So, I create an arraylist ArrayList<Number>, add Integers and Doubles, but when I call getVal with an element of the arrayList I get a compile error. If I cast it to an Integer It's fine, but this defeats my purpose.
I'm misunderstanding something. Here is my code.
import java.util.ArrayList;
public class Test{
public static int getVal(Integer x) {
return x.intValue();
}
public static double getVal(Double x) {
return x.doubleValue();
}
public static void main(String[] args){
ArrayList<Number> numbers = new ArrayList<Number>();
Integer x = new Integer(5);
Double y = new Double(1.2);
numbers.add(x);
numbers.add(y);
int intVal1 = getVal(x); //fine
int intVal2 = getVal((Integer)numbers.get(0)); //fine
int intVal2 = getVal(numbers.get(0)); //error, requires cast. why?
}
}
Thanks in advance for any help. How else could I have a collection of Integers and Doubles?