繁体   English   中英

为什么添加长变量会导致串联?

[英]Why does addition of long variables cause concatenation?

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将它们串联起来。

有人可以帮助我,为什么将两个原始变量串联在一起?

问候,瓜尔达

我的猜测是您实际上正在执行以下操作:

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"

我怀疑您没有看到自己认为的内容。 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
    }
}

暂无
暂无

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

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