传递“const” Java中的变量到方法 [英] Passing "const" variable to method in Java
问题描述
在Java中是否有一个等同于在C ++中传递const引用的方法?
不会忽略方法签名的constness误导?
Is there an equivalent in Java to the passing on const references in C++?
Isn't leaving out the "constness" misleading in regard to the method signature?
推荐答案
不,不是。
Javafinal const。以下(最终变量的延迟初始化)在Java中工作:
Java "final" is not an exact equivalent of C++ "const". The following (delayed initialization of a final variable) works in Java:
final double x;
int w = 1;
if (w > 2)
{
x = 0.5;
}
else
{
x = - 0.5;
}
但在C ++中不能使用final 。
but it doesn't work in C++ with "final" replaced by "const".
在方法声明中的变量上使用final在Java中很有用,因为允许你在方法内创建的任何匿名类中使用这个变量。
Using "final" on a variable in the method declaration can be useful in Java, because allows you to use this variable inside any anonymous class created inside your method.
PS。我首先对Java中缺少const感到失望,但后来学会了与final一起生活。
PS. I was first disappointed by the lack of "const" in Java but later learned to live with "final".
PS2。链接到此主题的Java词汇表( http://mindprod.com/jgloss/immutable.html )有一件事错误:不,你没有给出一个100%的guaranntee,最终变量不改变其值:
PS2. The Java glossary (http://mindprod.com/jgloss/immutable.html) linked to in this thread has one thing wrong: no, you are not given a 100% guaranntee that the final variable doesn't change its value:
1)它从未定义变为定义 ,但是编译器会告诉你是否在初始化之前引用它
1) it changes from "undefined" to "defined", but the compiler will tell you if you reference it before initialization
2)在Linux上,double存储在寄存器中时具有80位精度,但是64位当存储在内存中时。当最后的双变量被推出寄存器时,它将被截断并改变其值。正如Joel Spolsky所说,抽象造成了泄漏。
2) on Linux, a double has 80-bit precision when stored in a register, but 64-bit when stored in memory. When a final double variable is pushed out of the register, it will be truncated and change its value. As Joel Spolsky says, "abstraction has sprung a leak".
这篇关于传递“const” Java中的变量到方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!