Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);

后端 未结 9 1130
猫巷女王i
猫巷女王i 2020-12-01 21:04

Autoboxing seems to come down to the fact that I can write:

Integer i = 0; 

instead of:

Integer i = new Integer(0);


        
相关标签:
9条回答
  • 2020-12-01 21:39

    You kind of simplified it a little too much.

    Autoboxing also comes into play when using collections. As explained in sun's java docs:

    Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class. ... When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.

    So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

    Great overview of Autoboxing

    0 讨论(0)
  • 2020-12-01 21:40

    Adding to Lim's comment, primitives are stored on the stack, and primitive-wrappers, as objects, are stored on the heap... There are subtle implications due to this.

    0 讨论(0)
  • 2020-12-01 21:46

    The main advantage would be readability, syntactic sugar basically. Java is already very verbose, Sun is trying all sorts of ways to make the syntax shorter.

    0 讨论(0)
  • 2020-12-01 21:48

    With my cynical hat on: to make-up for limitations on the original Java (I mean Oak here) spec. Not just the first time.

    0 讨论(0)
  • 2020-12-01 21:49

    That is the idea, yes. It's even more convenient to be able to assign an Integer to an int, though.

    One could argue that autoboxing addresses a symptom rather than a cause. The real source of confusion is that Java's type system is inconsistent: the need for both primitives and object references is artificial and awkward. Autoboxing mitigates that somewhat.

    0 讨论(0)
  • 2020-12-01 21:49

    From what I remember from reading Joshua Bloch's Effective Java, you should consider the primitives over their boxed counterparts. Autoboxing without regard for its side effects can produce problems.

    0 讨论(0)
提交回复
热议问题