O método intern()
Para armazenar um String
em um String
piscina, usamos uma técnica chamada Estagiário de cordas. Aqui está o que Javadoc nos fala sobre o intern()
método:
/**
* Returns a canonical illustration for the string object.
*
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
*
* When the intern technique is invoked, if the pool already incorporates a
* string equal to this {@code String} object as decided by
* the {@hyperlink #equals(Object)} technique, then the string from the pool is
* returned. In any other case, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
*
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and provided that {@code s.equals
*
* All literal strings and string-valued fixed expressions are
* interned. String literals are outlined in part 3.10.5 of the
* The Java™ Language Specification.
*
* @returns a string that has the identical contents as this string, however is
* assured to be from a pool of distinctive strings.
* @jls 3.10.5 String Literals
*/ public native String intern();
O intern()
método é usado para armazenar String
está em um String
piscina. Primeiro, ele verifica se o String
que você criou já existe no pool. Se não, ele cria um novo String
na piscina. Nos bastidores, a lógica de String
o agrupamento é baseado em Padrão Flyweight.
Agora, observe o que acontece quando usamos o new
palavra-chave para forçar a criação de dois String
e: