There is a stack containing a long-sized range, and you want to multiply two values by popping them from the stack.
Stack<Long> s = new Stack<>();
s.push(1000000000);
s.push(1000000000);
long result = (long) s.pop() * (long) s.pop();
However, doing such an operation gives an error.
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.Long
what’s wrong with this code
>Solution :
There are a few issues here:
Stack<Long> s = new Stack();
This is actually a partially-raw type. You need to add <> on the right-hand side:
Stack<Long> s = new Stack<>();
(NB: I can remember at some point in the past encountering this as behaving like a raw type. I tried it on ideone just now, and it behaves like a non-raw type. I forget the exact situation in which it works like I describe – perhaps it was on Eclipse’s compiler…? Anyway, the point is: use the diamond, and it’s correct).
Because that’s raw, it leads on to the next point:
s.push(1000000000);
1000000000 is an int literal. You shouldn’t actually be able to add this to a Stack<Long>; you only can because of the partial rawness. int cannot be autoboxed to Long: you have to explicitly box it, or at least cast to long.
Stack stores objects; int 1000000000 gets boxed to Integer 1000000000, and put into the stack.
You need to push long literals (or Longs) instead:
s.push(1000000000L); // Note the L suffix
(long) s.pop()
Actually, this could almost work, if you’d written it like this:
s.pop().longValue()
But you’re still getting Integers out of it as it stands.
Note that if you’d added the values correctly, you wouldn’t need to put the (long) casts: Java would automatically unbox the values:
long result = s.pop() * s.pop();