Hashmap ejemplo de Daniel Shiffman.
Este ejemplo muestra cómo utilizar un HashMap para almacenar una colección de objetos referenciados por una clave. Esto es muy parecido a una matriz, sólo que en lugar de elementos de acceso con un índice numérico, se utiliza una cadena.
Si está familiarizado con las matrices asociativas de otros idiomas, se trata de la misma idea.
Un ejemplo más sencillo es CountingStrings que utiliza IntDict en lugar de HashMap.
Las clases de procesamiento IntDict, FloatDict, y StringDict ofrecen una manera más sencilla de Cuerdas de emparejamiento con números u otras cadenas. Aquí se utiliza un HashMap porque queremos asociar una cadena con un objeto personalizado, en este caso un objeto "Palabra" que almacena dos números. * En este ejemplo, las palabras que aparecen en un libro (Drácula) solamente son de color blanco mientras que las palabras del otro (Frankenstein) son de color negro.
HashMap<String, Word> words; // HashMap object void setup() { size(640, 360); // Create the HashMap words = new HashMap<String, Word>(); // Load two files loadFile("dracula.txt"); loadFile("frankenstein.txt"); // Create the font textFont(createFont("SourceCodePro-Regular.ttf", 24)); } void draw() { background(126); // Show words for (Word w : words.values()) { if (w.qualify()) { w.display(); w.move(); } } } // Load a file void loadFile(String filename) { String[] lines = loadStrings(filename); String allText = join(lines, " ").toLowerCase(); String[] tokens = splitTokens(allText, " ,.?!:;[]-\"'"); for (String s : tokens) { // Is the word in the HashMap if (words.containsKey(s)) { // Get the word object and increase the count // We access objects from a HashMap via its key, the String Word w = words.get(s); // Which book am I loading? if (filename.contains("dracula")) { w.incrementDracula(); } else if (filename.contains("frankenstein")) { w.incrementFranken(); } } else { // Otherwise make a new word Word w = new Word(s); // And add to the HashMap put() takes two arguments, "key" and "value" // The key for us is the String and the value is the Word object words.put(s, w); if (filename.contains("dracula")) { w.incrementDracula(); } else if (filename.contains("frankenstein")) { w.incrementFranken(); } } } } class Word { // Store a count for occurences in two different books int countDracula; int countFranken; // Also the total count int totalCount; // What is the String String word; // Where is it on the screen PVector position; Word(String s) { position = new PVector(random(width), random(-height, height*2)); word = s; } // We will display a word if it appears at least 5 times // and only in one of the books boolean qualify() { if ((countDracula == totalCount || countFranken == totalCount) && totalCount > 5) { return true; } else { return false; } } // Increment the count for Dracula void incrementDracula() { countDracula++; totalCount++; } // Increment the count for Frankenstein void incrementFranken() { countFranken++; totalCount++; } // The more often it appears, the faster it falls void move() { float speed = map(totalCount, 5, 25, 0.1, 0.4); speed = constrain(speed,0,10); position.y += speed; if (position.y > height*2) { position.y = -height; } } // Depending on which book it gets a color void display() { if (countDracula > 0) { fill(255); } else if (countFranken > 0) { fill(0); } // Its size is also tied to number of occurences float fs = map(totalCount,5,25,2,24); fs = constrain(fs,2,48); textSize(fs); textAlign(CENTER); text(word, position.x, position.y); } }