2013-12-18 19 views
5

Ho il seguente codice diPerché "==" a volte funziona con String.trim?

public static void main(String... args) { 

    String s = "abc"; 
    System.out.println(s.hashCode()); 
    String s1 = " abc "; 
    System.out.println(s1.hashCode()); 
    String s2 = s.trim(); 
    System.out.println(s2.hashCode()); 
    String s3 = s1.trim(); 
    System.out.println(s3.hashCode()); 
    System.out.println(); 
    System.out.println(s == s1); 
    System.out.println(s == s2); 
    System.out.println(s == s3); 
} 

OP:

96354 
32539678 
96354 
96354 

false -- Correct 
true -- This means s and s2 are references to the same String object "abc" . 
false -- s3=s1.trim()... which means s3="abc" yet s==s3 fails.. If the above conditon were to be considered (s==s2 is true..) , this should also be true.. 

Perché mi appare "false" quando controllo s == s3 ..

+3

@JigarJoshi - Dubito che sia un duplicato. L'OP sa quando usare '==' e 'equals()'.Questa domanda riguarda un caso specifico, in cui '==' si comporta diversamente per diverse situazioni. – SudoRahul

+1

@ R.J Quindi questa domanda non dovrebbe esistere .. (o l'OP deve solo rivedere alcuni degli altri duplicati sull'argomento) – user2864740

+3

@ user2864740 - Non sono d'accordo con te su questo. È una buona domanda che richiede un dubbio molto specifico. Non vedo perché questo non dovrebbe esistere. Votazione di riaprire – SudoRahul

risposta

2
public String trim() { 
    int len = value.length; 
    int st = 0; 
    char[] val = value; /* avoid getfield opcode */ 

    while ((st < len) && (val[st] <= ' ')) { 
     st++; 
    } 
    while ((st < len) && (val[len - 1] <= ' ')) { 
     len--; 
    } 
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 
} 

Come si può vedere nel tuo caso (System.out.println(s == s2);) this viene restituito, che sta puntando allo stesso riferimento che è il motivo per cui si ottiene vero.

+1

grazie mille amico .. – TheLostMind

5

becuase s1.trim() restituirà una nuova? esempio. Le stringhe sono immutabili così ogni volta una funzione applicata ad Archi quindi una nuova istanza verrà restituito e si utilizza == che confronta l'uguaglianza esempio

Edit: come suggerito da Chris Hayes e R.J.

trim è intelligente e restituisce this se non ci sono spazi da tagliare. Quindi nel secondo caso hai spazi bianchi 'abc' quindi in questo caso non sta restituendo this ma una nuova istanza di stringa.

codice sorgente del trim method

+0

@ RJ: questa è la mia domanda ... – TheLostMind

+1

@ RJ Perché 'trim' è intelligente e restituisce' questo 'se non ci sono spazi da tagliare. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.trim%28%29 –

+0

@RJ Probabilmente avrebbe ti ha salvato una grande quantità di dolore per essere stato più esplicito nel primo commento. :) –

1

vedere nella documentazione - http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim() -

A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

quando la stringa è rimanere lo stesso restituisce la stringa stessa data.

+0

Sì .. So che dovrei usare .equals() la mia domanda è perché s1.trim() restituisce un nuovo oggetto quando s.trim() non lo fa? ? – TheLostMind

2

Se dai un'occhiata a String.trim vedrai che alla fine chiama String.substring che a sua volta restituisce new String(...) se la stringa viene effettivamente ritagliata. Ecco perché == fallisce.

1

Il codice sorgente di Java 7 per java.lang.String.trim() (dal JDK installato) è:

public String trim() { 
    int len = value.length; 
    int st = 0; 
    char[] val = value; /* avoid getfield opcode */ 

    while ((st < len) && (val[st] <= ' ')) { 
     st++; 
    } 
    while ((st < len) && (val[len - 1] <= ' ')) { 
     len--; 
    } 
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 
} 

L'istruzione return afferma che se non v'è alcun cambiamento alla stringa di essere tagliati, allora questo viene restituito, quindi s == s2:

String s = "abc"; 
String s2 = s.trim(); 
System.out.println(s == s2); // is true 

Quando la stringa rifilato esigenze essere tagliato, java.lang.String.substring() è chiamato. Il codice sorgente per substring() in Java 7 è:

public String substring(int beginIndex, int endIndex) { 
    if (beginIndex < 0) { 
     throw new StringIndexOutOfBoundsException(beginIndex); 
    } 
    if (endIndex > value.length) { 
     throw new StringIndexOutOfBoundsException(endIndex); 
    } 
    int subLen = endIndex - beginIndex; 
    if (subLen < 0) { 
     throw new StringIndexOutOfBoundsException(subLen); 
    } 
    return ((beginIndex == 0) && (endIndex == value.length)) ? this 
      : new String(value, beginIndex, subLen); 
} 

quando la stringa viene rifilato deve essere tagliato, poi substring() restituisce una nuova stringa:

new String(value, beginIndex, subLen) 

È per questo che s! = s3: codice

String s = "abc"; 
String s1 = " abc "; 
String s3 = s1.trim(); 
System.out.println(s == s3); // is false 

Fonte per questa risposta è disponibile su GitHub here.

Problemi correlati