Processingには通常の1次元配列、2次元配列、動的配列の他にも、ハッシュマップ(連想配列)という便利な機能があります。JSONやXMLなどは、このハッシュマップを外部ファイルに保存したものだと考えてもいいでしょう。以下は、初心者向けに HashMapの意味が見た目でわかる Processingサンプルです。
テーマは「キーを押すと、その文字に対応した色の丸が出る」というものです。
HashMapは、ざっくり言うと、
名前 → 値のペアを保存する仕組みです。たとえば、
"red" → 赤色
"blue" → 青色
"green" → 緑色のように、言葉とデータをセットで覚えさせることができます。
サンプル1:キーを押すと色が変わるカラーボール

// 文字と色をセットで保存するHashMap
HashMap<String, Integer> colors = new HashMap<String, Integer>();
String currentColorName = "red"; // 現在選ばれている色の名前
void setup() {
size(500, 500);
noStroke();
// HashMapに「名前」と「色」を登録する
colors.put("red", color(255, 80, 80));
colors.put("blue", color(80, 140, 255));
colors.put("green", color(80, 220, 120));
colors.put("yellow", color(255, 220, 80));
}
void draw() {
background(255);
// 現在の色名から、対応する色を取り出す
int c = colors.get(currentColorName);
// 大きな円を描く
fill(c);
ellipse(width/2, height/2, 220, 220);
// 説明テキスト
fill(0);
textSize(20);
textAlign(CENTER);
text("Current color: " + currentColorName, width/2, 60);
textSize(16);
text("Press R / B / G / Y", width/2, height - 50);
}
void keyPressed() {
if (key == 'r') {
currentColorName = "red";
} else if (key == 'b') {
currentColorName = "blue";
} else if (key == 'g') {
currentColorName = "green";
} else if (key == 'y') {
currentColorName = "yellow";
}
}このサンプルで学べること
colors.put("red", color(255, 80, 80));これは、
"red" という名前に、赤色を登録するという意味です。
そして、
int c = colors.get(currentColorName);で、
現在選ばれている名前に対応する色を取り出すことができます。
サンプル2:キーごとに違う図形が出る
次は、HashMapを使って、キーごとに違う図形サイズを登録します。

HashMap<String, Float> sizes = new HashMap<String, Float>();
String currentSizeName = "small";
void setup() {
size(500, 500);
noStroke();
// 名前とサイズをセットで登録
sizes.put("small", 80.0);
sizes.put("medium", 160.0);
sizes.put("large", 260.0);
}
void draw() {
background(250);
// 現在の名前に対応するサイズを取り出す
float s = sizes.get(currentSizeName);
fill(80, 160, 255, 180);
ellipse(width/2, height/2, s, s);
fill(0);
textAlign(CENTER);
textSize(20);
text("Size: " + currentSizeName, width/2, 60);
textSize(16);
text("Press 1 / 2 / 3", width/2, height - 50);
}
void keyPressed() {
if (key == '1') {
currentSizeName = "small";
} else if (key == '2') {
currentSizeName = "medium";
} else if (key == '3') {
currentSizeName = "large";
}
}ポイント
この部分で、名前とサイズを対応させています。
sizes.put("small", 80.0);
sizes.put("medium", 160.0);
sizes.put("large", 260.0);つまり、
"small" → 80
"medium" → 160
"large" → 260という対応表を作っているイメージです。
