English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode intern() de String dans Java retourne la représentation normale de l'objet chaîne.
La syntaxe de la méthode intern() de la chaîne est :
string.intern()
Ici, string est un objet de la classe String.
Sans aucun paramètre
Retourne la représentation normale de la chaîne
L'implémentation de chaînes intégrées assure que toutes les chaînes de caractères ayant le même contenu utilisent la même mémoire.
Supposons que nous ayons deux chaînes de caractères :
String str1 = "xyz"; String str2 = "xyz";
En raison de str1and str2Ont le même contenu, donc ces deux chaînes partageront la même mémoire. Java insère automatiquement des chaînes littérales.
Cependant, si l'on crée des chaînes de caractères en utilisant la clé new, ces chaînes ne partageront pas la même mémoire. Par exemple,
class Main { public static void main(String[] args) { String str1 = new String("xyz"); String str2 = new String("xyz"); System.out.println(str1 == str2); // false } }
On cet exemple, on peut voir que les deux str1and str2with the same content. However, they are not equal because they do not share the same memory.
In this case, you can manually use the intern() method to use the same memory for strings with the same content.
class Main { public static void main(String[] args) { String str1 = new String("xyz"); String str2 = new String("xyz"); //str1and str2do not share the same memory pool System.out.println(str1 == str2); // false //uses the intern() method //Now, str1and str2both share the same memory pool str1 = str1.intern(); str2 = str2.intern(); System.out.println(str1 == str2); // true } }
As you can see, str1and str2with the same content, but they are not equal at first.
then, we use the intern() method so that str1and str2use the same memory pool. After using intern(), str1and str2equal.