0

I am asking this question because I have to a situation where I have the following two methods:

public T get(Serializable id) and
public T get(int id) 

I have to use the first method in most scenarios and the second method is already deprecated in our system.

My inputs are String so every time I need to call the get(Serializable id) , I have to pass Integer instead of int, otherwise it will use the second method which is deprecated. i.e I have to call Integer.parseInt(str) and then I have to Box it to Integer ( i.e (Integer)Integer.parseInt(str)) which seems redundant.

Is there a better way to do this and why is the implementation of Integer.parseInt(str) return int instead of Integer?

WowBow
  • 7,137
  • 17
  • 65
  • 103
  • 1
    A small point - you don't "*unbox to Integer*" - you box to `Integer`, and unbox to `int`; wrappers are primitives in a boxed form as they *box* the primitive into an `Object` – Andy Brown Sep 09 '15 at 18:01
  • @AndyBrown Thank you. I updated my question. – WowBow Sep 09 '15 at 18:06
  • Because everybody except you prefers it that way. – user207421 Sep 09 '15 at 18:09
  • 2
    No problem. On a side note when you ask *why* about the behaviour of a java core library feature, the answer is almost always "because thats the way it was built". So, you are usually asking a different hidden question, like "what is the shortest/fastest/most elegant way to do X" - always try and work out what that question is and you'll get what you want far quicker. The answers to the question I linked to have probably collectively covered most of the points you need. – Andy Brown Sep 09 '15 at 18:09
  • 2
    If `Integer.parseInt` returned an `Integer`, that would impose boxing overhead on _everyone who ever wanted to parse an integer ever._ Most people don't want a boxed `Integer`, they want an `int`, and the situation you're in where a boxed and unboxed type are treated differently is extremely rare (and you should prevent it whenever possible). – Louis Wasserman Sep 09 '15 at 18:31

1 Answers1

9

why is the implementation of Integer.parseInt(str) return int instead of Integer?

Because Integer.parseInt was designed to return int and that is its return type.

Is there a better way to do this...

If you want to get Integer instead of int use Integer.valueOf.

Pshemo
  • 122,468
  • 25
  • 185
  • 269