简体   繁体   English

Long a = Long.valueOf(1)或Long a = 1L之间有什么区别吗?

[英]Is there any difference between Long a = Long.valueOf(1) or Long a = 1L?

Just wondering if this and other related functions like those Integer is one of those things that one should not be bothered with and just go with Long a = 1L ; 只是想知道这个和其他相关函数是否是那些不应该被打扰的东西之一,只需要使用Long a = 1L ; simple and straightforward. 简单明了。

They are essentially the same, the compiler internally creates a call to Long.valueOf() when it has to convert a primitive long to a Long, this is called "boxing". 它们本质上是相同的,编译器在内部创建对Long.valueOf()的调用,当它必须将基元long转换为Long时,这称为“装箱”。

In normal code you should use the primitive type long, it is more efficient than Long. 在普通代码中,您应该使用long的原始类型,它比Long更有效。 You need Long only when you need objects, for example for putting long values into collections. 只有在需要对象时才需要Long,例如将long值放入集合中。

Let's see what happens under the covers. 让我们看看幕后发生了什么。 First, consider this: 首先,考虑一下:

public class Example {
    public static void main(String[] args) {
        Long a = Long.valueOf(1L);
        System.out.println(a);
    }
}

Compile this with javac Example.java . javac Example.java编译它。 Then disassemble it with javap -c Example . 然后用javap -c Example反汇编它。 The result is the following: 结果如下:

Compiled from "Example.java"
public class Example extends java.lang.Object{
public Example();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   lconst_1
   1:   invokestatic    #2; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
   4:   astore_1
   5:   getstatic   #3; //Field java/lang/System.out:Ljava/io/PrintStream;
   8:   aload_1
   9:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V
   12:  return

}

Ok, now change the program to the following: 好的,现在将程序更改为以下内容:

public class Example {
    public static void main(String[] args) {
        Long a = 1L;
        System.out.println(a);
    }
}

Compile and disassemble it again. 再次编译和反汇编。

You'll see that this version of the program compiles to exactly the same as the first version; 你会看到这个版本的程序编译成与第一个版本完全相同; the compiler has generated the call to Long.valueOf(...) automatically. 编译器自动生成对Long.valueOf(...)的调用。

See: Autoboxing 请参阅: Autoboxing

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

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