2

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 将它们连接起来。

任何人都可以帮助我,为什么连接两个原始变量?

问候,格尔达

4

2 回答 2

22

我的猜测是你实际上正在做类似的事情:

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"
于 2008-10-28T12:28:09.580 回答
4

我怀疑你没有看到你认为你看到的东西。Java 不这样做。

请尝试提供一个简短但完整的程序来演示这一点。这是一个简短但完整的程序,它演示了正确的行为,但使用了您的“错误”代码(即反例)。

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
    }
}
于 2008-10-28T12:15:22.290 回答