• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collections  RSS feed

 
bis ani
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Prior to Tiger, Java did not allow primitives to be used in Collection. Can anybody provide the reason why this was done and why it is changed now?

Also mostly when we use Collection, we use like
Collection C = new ArrayList();

What is wrong if I say, ArrayList alist = new ArrayList().
Why should I use the interface reference to hold my arraylist object?
I know there is no issue in coding part but i would like to know the design aspect of this?

Regards,
Bis
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why should I use the interface reference to hold my arraylist object?

Its always good practice to code to an interface. That way it doesn't matter which implementation of the interface you use, all will work.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java doesn't allow primitives in collections now, either, only objects. You can't declare an ArrayList<int>, for example. But Java does now have autoboxing, which is the automatic conversion of primitives to objects and vice-versa. It's just syntactic sugar for something you have always been able to do manually: you can always create an Integer to wrap an int, for example, and then store it in an ArrayList<Integer> .

While autoboxing is convenient, it's obviously not very efficient to be constantly wrapping and unwrapping primitives; a lot of possibly unneeded objects will be created. The danger is that some programmers won't know about it, and so will abuse it.

This is hardly an advanced topic. I'm moving this to JiG Intermediate.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!