Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can we add primitive variables in ArrayList or just objects?

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can we add primitive variables in arraylist or just objects
 
Chinna Eranna
Ranch Hand
Posts: 174
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can add *only* objects.

You can use.. wrapper classes.. for store the primitive data.
 
Karthick Dharani Vidhya
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With the AUTO BOXING feature, the below code will work fine



But even though you add primitive ones here, Auto boxing is done and all these values are added as Integer objects
 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karthick Dharani Vidhya wrote:With the AUTO BOXING feature, the below code will work fine



But even though you add primitive ones here, Auto boxing is done and all these values are added as Integer objects


why aint you used

 
Karthick Dharani Vidhya
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should have used it. Thanks.
 
Campbell Ritchie
Sheriff
Posts: 48448
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Hegde wrote:why aint you used

Surely you mean this?
 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ritchie sir , arent both correct?

i mean

ArrayList<Integer>a=new ArrayList<Integer>(); //as arraylist is a class

List<Integer>iList=new ArrayList<Integer>(); //list is an interface
 
Janeice DelVecchio
Saloon Keeper
Posts: 1808
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Hegde wrote:Ritchie sir , arent both correct?

i mean

ArrayList<Integer>a=new ArrayList<Integer>(); //as arraylist is a class

List<Integer>iList=new ArrayList<Integer>(); //list is an interface


Campbell's solution is best. It is my understanding that you should always code to an interface (when possible) and not its implementation.

I think this allows for greater flexibility if you need to change something down the line.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic