Reputation: 352
I made a little program to illustrate my question. If I strip the casting to BigInteger in the line of the return (12th line), I get a compiling error of "Incompatible types". But if I do the casting, the line before (11th) prints out that the type of the returned value is BigInteger. If it's a BigInteger, why do I have to cast?
public class ProbArrBig {
public static void main (String args[]) {
}
private static BigInteger myFunction() {
ArrayList myArr = new ArrayList();
BigInteger myNumber = BigInteger.valueOf(23452439);
myArr.add(myNumber);
System.out.println("Type of myArr.get(0): "+myArr.get(0).getClass().getName());
return (BigInteger) myArr.get(0); //Doesn't work without (BigInteger)
}
}
Upvotes: 0
Views: 1072
Reputation: 236
The ArrayList class is designed to take a generics type <E>
as follows:
ArrayList<Integer> myArr = new ArrayList<Integer>();
Since you did not provide the actual type for <E>
for your particular instance, what you actually have is
ArrayList<Object> myArr = newArrayList<Object>();
Therefore, your return of myArr does not match your method signature unless you cast BigInteger, which you are able to do because everything inherits from the Object class. If you change your method to return a type Object, you will see that the code will compile without error, without the cast.
Upvotes: 1
Reputation: 76
It should be using
ArrayList<BigInteger> myArr = new ArrayList<BigInteger>()
This is called generics and indicate that the list contains BigInteger objects, therefore when a value it is retrieved from the list you are indicating that it will be of that specific type.
Upvotes: 3