I was working on a problem when I encountered this.
(int)input.charAt(i) //works
(Integer)input.charAt(i) // Does not work
// input being a string
The first thought I have is primitives are treated differently and that is why this is not working. But then I find it difficult to understand why would they have a Integer Wrapper class in the first place.
Edit: What are the advantages of having wrapper classes then? Is it just for not having a primitives presence and being more OO in design? I'm finding it difficult to understand how are tehy helpful. New doubt altogetehr.
You're right that primitives are treated differently. The following would work:
(Integer)(int)input.charAt(i);
The difference is that when the argument is an int
, (Integer)
boxes the integer. It's not actually a cast even though it looks like it. But if the argument is a char
, then it would be a cast attempt; but primitives can't be cast to objects and therefore it doesn't work. What you can do is to first cast the char
to int
- this cast is okay since both are primitive types - and then the int
can be boxed.
Of course, char
-> Integer
boxing could have been made working. "Why not?" is a good question. Probably there would have been little use for such feature, especially when the same function can be achieved by being a little bit more explicit. (Should char
-> Long
work too, then? And char
-> Short
? chars are 16-bit, so this would be most straightforward.)
Answer to edit: the advantage of wrapper classes is that wrapped primitives can be treated like objects: stored in a List<Integer>
, for example. List<int>
would not work, because int
is not an object. So maybe even more relevant question would be, what are primitive non-objects doing in an OO language? The answer is in performance: primitives are faster and take less memory. The use case determines whether the convenience of objects or the performance of primitives is more important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With