Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections

 
Sathish kumar Santhosam
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why Collection allows object type not primitive type?
Is Wrapper Class introduced only for collections?

thanks in advance.

Sathish
 
Greg Charles
Sheriff
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2989
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great Greg! nice explanation.I Agree with you

In Java, Collection means collection of Objects, no more primitives.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just go through it, this is the API
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic