Zachowanie literałów String jest mylące
Zachowanie literałów String jest bardzo mylące w poniższym kodzie.
Rozumiem wiersze 1, 2 i 3true
, ale dlaczego linia 4false
?
Kiedy drukuję hashcode obu, są one takie same.
class Hello
{
public static void main(String[] args)
{
String hello = "Hello", lo = "lo";
System.out.print((Other1.hello == hello) + " "); //line 1
System.out.print((Other1.hello == "Hello") + " "); //line 2
System.out.print((hello == ("Hel"+"lo")) + " "); //line 3
System.out.print((hello == ("Hel"+lo)) + " "); //line 4
System.out.println(hello == ("Hel"+lo).intern()); //line 5
System.out.println(("Hel"+lo).hashCode()); //hashcode is 69609650 (machine depedent)
System.out.println("Hello".hashCode()); //hashcode is same WHY ??.
}
}
class Other1 { static String hello = "Hello"; }
wiem to==
sprawdza równość referencyjną i sprawdza literały w puli. wiemequals()
jest właściwy sposób. Chcę zrozumieć koncepcję.
Już to sprawdziłempytanie, ale to nie wyjaśnia jasno.
Byłbym wdzięczny za pełne wyjaśnienie.