긴 변수의 추가가 왜 연결을 유발합니까?
-
04-07-2019 - |
문제
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가 그들을 연결합니다.
누구든지 나를 도울 수 있는데, 왜 두 가지 원시 변수가 연결 되는가?
인사, 게르다
해결책
나는 당신이 당신이보고있는 것을 보지 못한다고 생각합니다. Java는 이것을하지 않습니다.
a 짧지 만 완전한 프로그램 이것을 보여줍니다. 다음은 올바른 동작을 보여주는 짧지 만 완전한 프로그램이 있지만 "잘못된"코드 (즉, 반례).
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"
제휴하지 않습니다 StackOverflow