为什么添加长变量会导致连接?
问题描述:
Java在执行加法时如何处理长变量?为什么添加长变量会导致连接?
版本错误1:
Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??
版本错误2:
Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??
正确的版本:
Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct
我不明白,为什么Java的将它们连接起来。
任何人都可以帮助我,为什么两个原始变量是连接的?
问候,guerda
答
我怀疑你没有看到你认为你所看到的。 Java不会这样做。
请尝试提供一个short but complete program来说明这一点。这是一个简短但完整的程序,它表明了正确的行为,但是却带有“错误的”代码(即反例)。
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector speeds = new Vector();
speeds.add("x");
speeds.add("y");
long estimated = 1l;
long time = speeds.size() + estimated;
System.out.println(time); // Prints out 3
}
}
答
我的猜测是,你实际上是在做喜欢的事:
System.out.println("" + size + estimated);
这个表达式被从左到右依次为:
"" + size <--- string concatenation, so if size is 3, will produce "3"
"3" + estimated <--- string concatenation, so if estimated is 2, will produce "32"
为了得到这个工作,你应该做的:
System.out.println("" + (size + estimated));
再次这是从左向右计算:
"" + (expression) <-- string concatenation - need to evaluate expression first
(3 + 2) <-- 5
Hence:
"" + 5 <-- string concatenation - will produce "5"
提示:不要使用“L”为多头,因为它是从“1”没有区别在某些字体。改用'L'。 – toolkit 2008-10-28 12:18:06
你已经接受了一个答案,但是没有完全解释是什么导致了这个问题 - 你能否详细说明一下? – paxdiablo 2008-10-28 12:45:47