/***************************************************************/ /* Prof. Dr. Carsten Vogt */ /* FH Koeln, Fak. 07 / Nachrichtentechnik */ /* http://www.nt.fh-koeln.de/vogt */ /* */ /* Das Programm demonstriert Basismethoden auf HashMaps. */ /* Mit HashMaps werden Paare aus Schluesseln und Werten */ /* verwaltet. */ /* Bei HashMaps sind, im Unterschied zu TreeMaps, die Ein- */ /* traege in keiner bestimmten Reihenfolge angeordnet. */ /* Das Programm ist erst ab Java 5 lauffaehig! */ /***************************************************************/ import java.io.*; import java.util.*; public class HashMaps { public static void main(String[] args) { /* Deklaration und Erzeugung einer HashMap = ungeordnete Folge von Paaren (Schluessel,Wert) */ HashMap tab = new HashMap(); System.out.println(); System.out.println("Hinzufuegen von sechs Eintraegen:"); System.out.println(" tab.put(3,\"Drei\")"); System.out.println(" analog mit 1, 4, 2, 6, 5"); tab.put(3,"Drei"); tab.put(1,"Eins"); tab.put(4,"Vier"); tab.put(2,"Zwei"); tab.put(6,"Sechs"); tab.put(5,"Fuenf"); /* Ueberpruefung, ob bestimmte Schluessel in der Tabelle sind */ System.out.println(); System.out.println("tab.containsKey(2): "+tab.containsKey(2)); System.out.println("tab.containsKey(9): "+tab.containsKey(9)); /* Ueberpruefung, ob bestimmte Werte in der Tabelle sind */ System.out.println(); System.out.println("tab.containsValue(\"Zwei\"): "+tab.containsValue("Zwei")); System.out.println("tab.containsValue(\"Neun\"): "+tab.containsValue("Neun")); /* Suche nach Werten anhand von Schluesseln */ System.out.println(); System.out.println("tab.get(2): "+tab.get(2)); System.out.println("tab.get(6): "+tab.get(6)); System.out.println("tab.get(9): "+tab.get(9)); /* Ausgabe der Schluessel in der HashMap */ Collection menge = tab.keySet(); System.out.println(); System.out.println("tab.size(): "+tab.size()); System.out.println(); System.out.print("Schluessel in der HashMap: "); for (Iterator it=menge.iterator();it.hasNext();) System.out.print(it.next()+" "); System.out.println(); /* Ausgabe der Werte in der HashMap */ menge = tab.values(); System.out.println(); System.out.print("Werte in der HashMap: "); for (Iterator it=menge.iterator();it.hasNext();) System.out.print(it.next()+" "); System.out.println(); /* Entfernen von Eintraegen */ System.out.println(); System.out.println("Ausfuehrung von tab.remove(2)"); tab.remove(2); System.out.println("Ausfuehrung von tab.remove(4)"); tab.remove(4); menge = tab.values(); System.out.println(); System.out.print("Werte in der HashMap: "); for (Iterator it=menge.iterator();it.hasNext();) System.out.print(it.next()+" "); System.out.println(); } }