CKTIS / Java
Objects.hash: un codice hash a partire da due campi
Combina due campi in un codice hash di tipo `int`, scopri perché Java converte automaticamente un `int` in `Integer` e distingui `Objects.hash` da `Objects.hashCode`.
Versione: Java SE 21
Sintassi
import java.util.Objects;
// Java SE 21 — method declaration in java.util.Objects:
// public static int hash(Object... values)
int hash = Objects.hash(label, number); // label: String, number: intIn Java SE 21, il metodo statico Objects.hash(Object... values) di java.util.Objects restituisce un codice hash di tipo int per una sequenza ordinata di valori. In Objects.hash(label, number), Java converte automaticamente il campo number di tipo int in Integer (autoboxing) e passa entrambi i valori in un array Object[].
Il risultato segue Arrays.hashCode(Object[]): se l’array non è null, si parte da h = 1 e si applica h = 31 * h + (e == null ? 0 : e.hashCode()) per ogni elemento e. L’ordine può cambiare il risultato. Objects.hash() restituisce 1, Objects.hash((Object) null) restituisce 31 e Objects.hash((Object[]) null) restituisce 0.
Con un solo elemento, Objects.hash(x) combina comunque il suo codice hash con il valore iniziale. Objects.hashCode(x) restituisce direttamente x.hashCode(), oppure 0 se x è null. Un Object[] esistente passato come unico argomento funge da array dei varargs; con un cast a Object diventa un solo elemento, il cui contenuto non viene sottoposto a hashing ricorsivo.
Quando implementi hashCode(), combina i campi in modo coerente con il confronto eseguito da equals. Oggetti uguali devono avere lo stesso codice hash, ma anche oggetti diversi possono averlo. Non usare il risultato come identificatore persistente o come hash crittografico: il contratto generale di hashCode() non garantisce lo stesso valore tra esecuzioni.
Esempi
import java.util.Objects;
public class Main {
record Key(String label, int number) {
@Override
public int hashCode() {
return Objects.hash(label, number);
}
}
public static void main(String[] args) {
Key first = new Key("A", 7);
Key second = new Key("A", 7);
System.out.println(first.equals(second));
System.out.println(first.hashCode() == second.hashCode());
System.out.println(first.hashCode());
System.out.println(Objects.hash(7));
System.out.println(Objects.hashCode(7));
}
}Risultato
true true 2983 38 7
Il metodo `equals` generato per `Key` confronta entrambi i componenti del record. Le prime due righe (`true`) mostrano che gli oggetti sono uguali e che i loro codici hash coincidono. `2983` combina i codici di `"A"` e `7`; `38` e `7` distinguono il codice di una sequenza di un solo elemento da quello dell’elemento stesso.
Lezioni correlate
- Java · Lezione 18 · Avanzato · Versione: 2
Fonti
- Objects — hash(Object...) and hashCode(Object), Java SE 21
- Arrays — hashCode(Object[]), Java SE 21
- List — hashCode(), Java SE 21
- Java Language Specification, Java SE 21 — §5.1.7 Boxing Conversion
- Java Language Specification, Java SE 21 — §15.12.4.2 Evaluate Arguments
- Object — hashCode(), Java SE 21
- Record — equals(Object), Java SE 21
- String — hashCode(), Java SE 21
- Integer — hashCode(), Java SE 21