声明/初始化原语等于创建新对象
声明/初始化原语与创建新对象相同吗?据我所知,当我们创建原语时,我们还为它们创建包装类。顺便说一句,我在java上实现。
is declaring/initializing primitives the same as creating new objects? from what i know when we create primitives, we also creating wrapper classes for them. im implementing on java btw.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,分配原始值不会创建任何对象。
您可能指的是这样一个事实:当在需要引用类型(也称为“对象”)的上下文中使用基元值时,它们可以自动装箱到相应的包装器中:
另外,我将尝试描述声明和初始化之间的区别:
变量在第一次创建时被“声明”(即指定变量的类型和名称)。 在声明期间被赋值时它就会被初始化。
No, assigning primitive values does not create any objects.
What you might be referring to is the fact that primitive values can be auto-boxed into the corresponding wrappers, when they are used in a context where a reference type (a.k.a "an object") is required:
Also, I'll try to describe the difference between declare and initialize:
A variable is "declared" when it is created for the first time (i.e. you specify the type and name of the variable). It is initialized when it's assigned a value during declaration.
不,声明和初始化原始变量不会创建对象。让我们采用一个具有两个整数值的类 - 一个使用包装类型,一个不使用。
primitive
变量的值就是数字 10。wrapper
变量的值是一个引用一个Integer
对象,该对象又包含数字 10。因此Foo
的实例将保留primitive
中的数字和primitive
中的引用的状态代码>包装。Java 中的所有基本类型都有包装类,但您不会自动使用它们。
No, declaring and initializing a primitive variable does not create an object. Let's take a class with two integer values - one using the wrapper type and one not.
The value of the
primitive
variable is just the number 10. The value of thewrapper
variable is a reference to anInteger
object which in turn contains the number 10. So an instance ofFoo
would keep state for the number inprimitive
and the reference inwrapper
.There are wrapper classes for all primitive types in Java, but you don't use them automatically.
创建一个基元不会也会为它们创建一个包装类。
至于你原来的问题:声明/初始化一个原语将在堆栈上创建它,而声明一个对象将分配一个变量来保存对对象的引用。初始化对象将在堆上分配它。
Creating a primitive DOES NOT also create a wrapper class for them.
As for your original question: Declaring/initializing a primitive will create it on the stack, whereas declaring an object will allocate a variable to hold a reference to an object. Initializing the object will allocate it on the heap.
答案:不。
请查看:http://java.lang. sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
Answer: No.
Check this out: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
不。原语不是 java 中的对象。
No. Primitives are not objects in java.