aspose file tools*
The moose likes Java in General and the fly likes Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Collections" Watch "Collections" New topic
Author

Collections

Sathish kumar Santhosam
Greenhorn

Joined: Sep 20, 2010
Posts: 1
Why Collection allows object type not primitive type?
Is Wrapper Class introduced only for collections?

thanks in advance.

Sathish
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

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.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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.
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

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.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Great Greg! nice explanation.I Agree with you

In Java, Collection means collection of Objects, no more primitives.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

I just go through it, this is the API
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections
 
Similar Threads
Map Question
collections and generics
TypeSafety differences
How to make all collections(List,Map..etc..) type safe in java?
garbage collection listener for cache cleanup