Perché l'aggiunta di variabili lunghe provoca la concatenazione?
-
04-07-2019 - |
Domanda
Cosa fa Java con le variabili lunghe mentre esegue l'aggiunta?
Versione 1 errata:
Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??
Versione errata 2:
Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??
Versione corretta:
Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct
Non capisco, perché Java li concatena.
Qualcuno può aiutarmi, perché due variabili primitive sono concatenate?
Saluti, guerda
Soluzione
Sospetto che non vedi quello che pensi di vedere. Java non lo fa.
Prova a fornire un programma breve ma completo che lo dimostra. Ecco un programma breve ma completo che dimostra il comportamento corretto, ma con il tuo "sbagliato" codice (ovvero un controesempio).
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
}
}
Altri suggerimenti
Suppongo che stai effettivamente facendo qualcosa del tipo:
System.out.println("" + size + estimated);
Questa espressione viene valutata da sinistra a destra:
"" + size <--- string concatenation, so if size is 3, will produce "3"
"3" + estimated <--- string concatenation, so if estimated is 2, will produce "32"
Per farlo funzionare, dovresti fare:
System.out.println("" + (size + estimated));
Anche in questo caso viene valutato da sinistra a destra:
"" + (expression) <-- string concatenation - need to evaluate expression first
(3 + 2) <-- 5
Hence:
"" + 5 <-- string concatenation - will produce "5"