3 ms·
Not entirely correct, last I checked string interning was ONLY guaranteed for those strings defined in source and read in during class loading, strings created
by whizzter 3y ago
Not entirely correct, last I checked string interning was ONLY guaranteed for those strings defined in source and read in during class loading, strings created via the String constructor (f.ex. via StringBuilder) CAN duplicate those strings that you hardcoded in your sources, to get the "canonical" string in those cases you have to invoke String.intern() if memory serves me correct.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#intern https://docs.oracle.com/en/java/javase/11/docs/api/java.base...()
Also interning strings to optimize equality checks to be able to use pointer comparison is dangerous for external inputs since iirc at some point interned strings could permanently be stored (unless implemented by a WeakSet) and attackers could fill up your heap (or cause other GC issues since the entire interning functionality is a cache) by filling up your interning lists with crap.
- xxs 3y ago>String being equal by reference is important, and part of JLS. I never said String must be equal by reference when their content is. However string literals must be equal by reference. I thought Mentioning the JLS would make it obvious, esp. having 'intern' in the context
- ywei3410 3y agoThere's also the new JVM option which eludes me at the moment which sweeps the strings which are promoted to the older generation and interns them. Not certain about whether `String.intern` is permanently stored; I rather suspect that it sweeps the existing strings since iirc the java string has a hash associated with it anyway.