質問

追加の実行中に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がそれらを連結する理由。

誰でも私を助けることができます、なぜ2つのプリミティブ変数が連結されていますか?

挨拶、ゲルダ

役に立ちましたか?

解決

あなたがあなたが見ていると思うものを見ていません。 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
    }
}

他のヒント

あなたは実際に次のようなことをしていると思います:

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"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top