English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Se la chiave specificata non è presente nel HashMap, il metodo putIfAbsent() di Java HashMap inserisce la mappatura chiave/valore nel HashMap.
La sintassi di putIfAbsent() è:
hashmap.putIfAbsent(K key, V value)
putIfAbsent() ha due parametri.
key - Il valore specificato è mappato alla chiave
value - Il valore è associato alla chiave
Se la chiave specificata esiste già nella hash, viene restituito il valore associato alla chiave.
Se la chiave specificata non esiste nel mappatura hash, viene restituito null
Attenzione: se è stato specificato previamente un valore null, ritorna null valore。
import java.util.HashMap; class Main { public static void main(String[] args){ // crea HashMap HashMap<Integer, String> languages = new HashMap<>(); // aggiungi mappature a HashMap languages.put(1, "Python"); languages.put(2, "C"); languages.put(3, "Java"); System.out.println("Languages: " + languages); //La chiave non è presente in HashMap languages.putIfAbsent(4, "JavaScript"); //La chiave è presente in HashMap languages.putIfAbsent(2, "Swift"); System.out.println("Aggiornati Languages: " + languages); } }
Risultato dell'output
Languages: {1=Python, 2=C, 3=Java} Languages aggiornate: {1=Python, 2=C, 3=Java, 4=JavaScript}
Nell'esempio sopra, abbiamo creato una hashtable chiamata languages. Attenzione a questa riga:
languages.putIfAbsent(4, "JavaScript");
In questo caso, la chiave 4 non è associata a nessun valore. Pertanto, il metodo putIfAbsent() aggiunge la mappatura {4 = JavaScript} all'hashtable.
Attenzione a questa riga:
languages.putIfAbsent(2, "Swift");
In questo caso, la chiave 2 è associata al valore Java. Pertanto, il metodo putIfAbsent() non aggiunge la mappatura {2 = Swift} all'hashtable.
AttenzioneAbbiamo aggiunto una singola mappatura all'hashtable utilizzando il metodo put(). Per ulteriori informazioni, visitareMetodo put() HashMap Java.