Somebody asked me: can an array in java contain integers and floats? She got that question from a teacher.
Now my answer was: yes, since you can declare an array of objects and store integers and floats in it.
But now I’m wondering if that is correct, since technically when you store Integer and Float objects in an array, it kind of does contain both types, but if you would “ask” the array he would tell you he contains Objects, and if I don’t do bookkeeping or class checks there’s no way to tell that there are integers and floats in the array.
On the other hand I still feel it might be the right answer since theoretically the array contains objects of both types.
So I’m asking for a smart opinion: if you were asked (in an interview, a test whatever) wether in java an array can contain integers and floats, yes or no? What would you answer?
A
intoffloatdoes not fit into aObject[]array. However, by autoboxing java will put aFloatorIntegerinto the array instead.Both
FloatandIntegerextendNumber. So you can even make a array of numbersNumber[]Also, you can put a
intinto afloat[], but java will then cast the int into a float. The other way around is also possible, but precision will be lost. (edit: Even from int->float precision can be lost. float->int may lose information about the overall magnitude of the value).The conclusion would depend on the question. For primitive datatypes a array can not contain the other datatype. If you use a Object array (Integer, Float, Number) the answer would be yes.