Se due String
s non sono identici, perché utilizzare le stringhe come chiavi in un HashMap
senza utilizzare lo stesso oggetto String
?Perché posso utilizzare le stringhe come chiavi in una HashMap?
String s1 = "Test";
String s2 = "Test";
System.out.println(s1 == s2); // should be false
System.out.println(s1.equals(s2)); // should be true
HashMap<String, String> map = new HashMap();
map.put(s1, "foo");
System.out.println(map.get(s2)); // should be "foo"--but why?
Fa HashMap
hanno qualche comportamento speciale per String
oggetti? In caso contrario, perché è possibile utilizzare due stringhe "diverse" per inserire e ottenere valori da un hash?
Si noti che 's1 == s2' sarà' true' a causa dell'internamento della stringa. –
Allora perché è pratica normale usare '.equals()' per confrontare 'String's? –
@Ted Hopp s1 == s2 sarà vero a causa del * pooling costante *. – EJP