• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

When to use Integer or new Integer

 
Ranch Hand
Posts: 2206
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone tell me which I should use and explain?




 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic