Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use Integer or new Integer

 
Steve Dyke
Ranch Hand
Posts: 1679
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone tell me which I should use and explain?




 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on what the attribute stored in the session actually is.

If it's an Integer object, there's absolutely no point converting it to a String and then back to an Integer. Just cast it straight to an Integer, as in the first approach.

If it's really a String, I'd cast it to a String and then use Integer.parseInt to convert it:
int edindex = Integer.parseInt((String)request.getSession().getAttribute("e8DIndexNumber"));

I don't think I'd ever use your second form exactly like that.
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:I don't think I'd ever use your second form exactly like that.

Agreed. One should never use the new keyword to convert to an Integer unless a new instance is required.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which is just about never. All of the primitive-wrapper classes have static valueOf methods which may use cached objects, reducing the memory footprint of your application. You should use those as much as possible. I never use new in combination with the primitive-wrapper classes anymore.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic