String it is fundamental part of any modern programing language and just sa important as a number. That why can propose that Java programers must have strong knowledge about String, but, unfortunately not all programers.
Today I started read news and saw an interesting string, that very confused me.
protected final static String fVersionSymbol = "version".intern();
intern() main algorithm:
Method intern() simply before creating a String object check exist or not exist this object in String pool and return this object. Otherwise create new object in the pool.
All strings in Java already interned. That why "Hel" + "lo" == "Hello" return true.
Today I started read news and saw an interesting string, that very confused me.
protected final static String fVersionSymbol = "version".intern();
Next I found more strings declared like that. What is intern()? You know, exists two different way to compare objects in Java. You can use operator ==, or you can use method equals(). Operator == compare link is two link on one object, and equals() compare is two object contains the same data.
One of the first lessons, what you get when you start learn about String in Java is that for compare two strings you should use equals() and no ==. If compare new String("Hello")==new String("Hello") you get in result false, because this is two different object with the same data. if you use equals(), you get true. Unfortunately equals() can be more slowest than ==, because it does string compare by characters.
Operator == check identity, all what it must do is compare two index and obviously it will much faster than equals(). That if you want compare the same string manu times, you can get a significant performance advantage through the use of checking the identity of objects instead of comparing characters.
intern() main algorithm:
- Create a hash set strings
- Check, that string (like characters sequence), with which we working, already in hash set
- If yes, use string from hash set
- Otherwise, add this string in hash set and after use it
Using this algorithm you guaranteed, that if two strings are identical sequences characters, they are one instance of a class. It's mean that you can easy compare strings using == instead of equals(), get a significant performance advantage when repetitive comparison.
Fortunately Java already includes implementation of this algorithm. This method intern() in class java.lang.String. Expresion new String("Hello").intern() == new String("Hello").intern() return true, otherwise with out intern() return false.
Method intern() simply before creating a String object check exist or not exist this object in String pool and return this object. Otherwise create new object in the pool.
All strings in Java already interned. That why "Hel" + "lo" == "Hello" return true.
No comments:
Post a Comment