简体   繁体   English

Java对象初始化-何时需要?

[英]Java object initialization - When is it necessary?

I'm curious about java initialization: 我对Java初始化感到好奇:
When is it necessary to initialize objects like this: 什么时候需要初始化这样的对象:

String init = new String("");

and which objects - like Strings - don't have to be initialized like above? 哪些对象(如字符串)不必像上面那样初始化?

String init = "";

From your comment on your question: 根据您对问题的评论:

Then my question is which objects need the "new Object()" initialization? 然后我的问题是哪些对象需要“ new Object()”初始化?

You're asking about construction , not initialization. 您是在问构造 ,而不是初始化。

All objects need to be constructed by someone. 所有对象都需要由某人构造。 The strings created by string literals are constructed by the JVM. 由字符串文字创建的字符串由JVM构造。 You basically never want to use new String("text content here") . 基本上,您永远都不想使用new String("text content here")

There are several other objects constructed by the JVM, such as the Class object for each class you load. JVM还构造了其他几个对象,例如您加载的每个类的Class对象。 But other than String , for objects you want to interact with, you usually either have to explicitly construct them (via new ) or receive them from a method that constructs them. 但是,除了String ,对于要与之交互的对象,通常要么必须显式地构造它们(通过new ),要么从构造它们的方法中接收它们。 String is a bit special because it's the only object type in Java (I think ) with a literal notation. String的情况比较特殊,因为它是在Java中的唯一对象类型(我认为 )用文字符号。 (All of the other literals, like 42 or false , are primitives.) (所有其他文字,如42false ,都是原语。)

Basically there's a subtle difference between the 2 ways of initialization you mentioned: When you use: 基本上,您提到的两种初始化方法之间有细微的差别:使用时:

String str = new String("");

a new String object is created on the heap and str points to it. 在堆上创建一个新的String对象,并且str指向该对象。

But in the latter case: 但在后一种情况下:

String str = "";

If there is already a string with this value ("") on the string pool , then the reference is initialized to point to it and no new object is created. 如果字符串池上已经存在一个带有该值(“”)的字符串 ,则引用将初始化为指向它,并且不会创建新对象。 If it is not found in the string pool, then a new string is created in the string pool and str is initialized to point to it. 如果在字符串池中找不到该字符串,则会在字符串池中创建一个新字符串,并初始化str指向它。

For strings, you almost always want to use the second form. 对于字符串,您几乎总是想使用第二种形式。 It does less work for what -- in most circumstances -- is the same result. 在大多数情况下,即使结果相同,它所做的工作也较少。

The same advice goes for numeric classes, such as Integer , Double , etc. 同样的建议适用于数字类,例如IntegerDouble等。

In all other cases you don't normally have the choice, and have to use the first form. 在所有其他情况下,您通常没有选择权,而必须使用第一种形式。

In Java, all objects must be initialized. 在Java中,必须初始化所有对象。 The second case init = "" is also an initialization, except that the compiler lets you avoid the explicit call: object creation is still there. 第二种情况init = ""也是一个初始化,除了编译器使您避免显式调用:对象创建仍然存在。 Starting with Java 5, the compiler also "knows" about wrappers for Java primitives, letting you use primitive constants in expressions that require a wrapper class (this is called autoboxing ). 从Java 5开始,编译器还“了解” Java原语的包装器,使您可以在需要包装器类的表达式中使用原语常量(这称为autoboxing )。

All local variables must be initialized explicitly, while member fields can be initialized implicitly to null or the default value of the primitive. 所有局部变量必须显式初始化,而成员字段可以隐式初始化为null或原语的默认值。

All Objects have to be initialized with new but some, like these for example: 所有对象都必须用new初始化,但有些要初始化,例如:

 String myString= "";
 Integer myInteger= 2;
 Float myFloat= 2f;
 Double myDouble= 2d;
 Byte myByte = 2;

and every kind of array, which can be initialized like `T[] array = {//list some Ts}; 以及每种类型的数组,都可以像`T [] array = {//列出一些Ts}那样进行初始化;

String s1 = "1";
String s2 = new String("2");
int i1 = 1;
int i2 = new Integer(2);
long l1 = 1l;
long l2 = new Long(2l);
float f1 = 1f;
float f2 = new Float(2f);
double d1 = 1d;
double d2 = new Double(2d);
char c1 = '1';
char c2 = new Character('2');
byte b1 = 1;
byte b2 = new Byte((byte) 2);
int[] a1 = {1};
int[] a2 = new int[] {2};

Most classes require explicit construction (the new), however a few classes does not, these are the autoboxing classes (String, Integer, Double, and a few more, as well as arrays of these (using the comma seperated list initiliazation)) and these are the only ones! 大多数类都需要显式构造(新的),但是一些类则不需要,它们是自动装箱类(String,Integer,Double等),以及它们的数组(使用逗号分隔列表初始化)和这些是唯一的!

What happens at the compiler level is really just that the compiler translates the implicit construction to an explicit one (eg One using new) 实际上,在编译器级别发生的只是编译器将隐式构造转换为显式构造(例如,使用new的构造)。

All objects need to be initialized before they can be used. 必须先初始化所有对象,然后才能使用它们。 You can try declaring: 您可以尝试声明:

int myPrimitiveInt;
Integer myObjectInt;

But myPrimitiveInt cannot be used until you give it a value, and myObjectInt is implicitly initialized as null. 但是,除非给它一个值,否则无法使用myPrimitiveInt,并且myObjectInt隐式初始化为null。 For either of these to be used (except to get a null from the object), they need to be given a value, whether you use a constructor or not. 对于要使用的任何一种(从对象中获取null除外),无论是否使用构造函数,都需要为它们提供一个值。

myPrimitiveInt = 5;
myObjectInt = new Integer(5);
myObjectInt = 5;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM