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?
解决方案
No, there isn't.
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;
}
but it doesn't work in C++ with "final" replaced by "const".
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. I was first disappointed by the lack of "const" in Java but later learned to live with "final".
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) it changes from "undefined" to "defined", but the compiler will tell you if you reference it before initialization
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".