You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中包装类无需构造方法调用?为何无需new关键字实例化?

Why Can We Create Wrapper Class Objects Without new or Constructor Calls in Java?

Great question—this is one of those Java "syntactic sugar" features that makes code cleaner, but it's easy to miss what's happening under the hood. Let's break it down step by step:

1. It's All About Autoboxing (Java 5+)

Starting with Java 5, the compiler introduced autoboxing—a feature that automatically converts primitive types to their corresponding wrapper class objects (and vice versa, with unboxing). When you write code like:

Integer myInt = 10;

You aren't skipping object creation entirely—instead, the compiler secretly rewrites your code to call a factory method for you:

Integer myInt = Integer.valueOf(10);

This is why you don't need to type new Integer(10) explicitly; the compiler handles the conversion behind the scenes.

2. Factory Methods + Object Caching = Performance Wins

The valueOf() method (available for all wrapper classes like Integer, Long, Byte, etc.) doesn't always create a new object. For commonly used values, Java maintains a cache pool of pre-created wrapper objects to avoid unnecessary memory allocation.

For example:

  • Integer caches values from -128 to 127 (this range can be extended with a JVM flag).
  • Byte, Short, Long cache all their possible values (since their ranges are small).
  • Character caches values from \u0000 to \u007F (ASCII characters).

So when you write Integer x = 5;, you're actually reusing an existing object from the cache instead of creating a new one—this is way more efficient than using new Integer(5) every time.

3. The Difference Between valueOf() and new

To make this concrete, compare these two lines:

Integer cachedInt = Integer.valueOf(5); // Reuses cached object
Integer newInt = new Integer(5); // Always creates a new object

If you check cachedInt == newInt, it will return false because they're different objects. But cachedInt.equals(newInt) returns true since their values are the same.

Wrapping Up

The ability to create wrapper objects without new is just Java making your code more readable via autoboxing. Underneath, it's using factory methods that leverage caching to boost performance. It's a nice convenience that saves you from writing repetitive boilerplate code!

内容的提问来源于stack exchange,提问作者Akshat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:09:30