Forums Register Login

Collections

+Pie Number of slices to send: Send
Why Collection allows object type not primitive type?
Is Wrapper Class introduced only for collections?

thanks in advance.

Sathish
+Pie Number of slices to send: Send
Welcome to JavaRanch!

The Collection classes don't allow primitives so they can enforce type safety. This works into the idea of generics, which you may not have studied yet, but you'll see when you get there. Basically, if I tell my Collection I only want to store Integers in it, but then I try to store a Float, or a Boolean, I'm going to get an error at compile time, where it's easy to fix.

Wrapper classes are great for storing otherwise primitive values in collections, especially because of autoboxing, but that's not their only use.
+Pie Number of slices to send: Send
 

Greg Charles wrote:Welcome to JavaRanch!

The Collection classes don't allow primitives so they can enforce type safety. This works into the idea of generics, ...


Most of the reason likes this. But, my doubt is, What about the pre-generics collections? Why don't they allow primitives?

BTW, there are some separate collections APIs for primitives.
+Pie Number of slices to send: Send
Fair enough. There's also the matters of internal data structures and interfaces. Many of the Collection classes will store the data in an Object array (Object []) so no primitives there. Even if that weren't an issue, the primitives would require different accessors and mutuators. You can overload the adds, but the gets still return Objects, and the only way around that is to write things method like getAsInt, getAsDouble, etc. Very ugly.

What collections allow primitives? Other than arrays of course.
+Pie Number of slices to send: Send
Great Greg! nice explanation.I Agree with you

In Java, Collection means collection of Objects, no more primitives.
+Pie Number of slices to send: Send
I just go through it, this is the API
I'm thinking about a new battle cry. Maybe "Not in the face! Not in the face!" Any thoughts tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 776 times.
Similar Threads
Map Question
How to make all collections(List,Map..etc..) type safe in java?
garbage collection listener for cache cleanup
TypeSafety differences
collections and generics
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 01:21:33.