2015-12-15 11:47:04 -08:00
|
|
|
// collectionsindepth/AssociativeArray.java
|
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Associates keys with values
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2015-09-07 11:44:36 -06:00
|
|
|
public class AssociativeArray<K, V> {
|
2015-06-15 17:47:35 -07:00
|
|
|
private Object[][] pairs;
|
|
|
|
private int index;
|
|
|
|
public AssociativeArray(int length) {
|
|
|
|
pairs = new Object[length][2];
|
|
|
|
}
|
|
|
|
public void put(K key, V value) {
|
|
|
|
if(index >= pairs.length)
|
|
|
|
throw new ArrayIndexOutOfBoundsException();
|
|
|
|
pairs[index++] = new Object[]{ key, value };
|
|
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
|
|
public V get(K key) {
|
|
|
|
for(int i = 0; i < index; i++)
|
|
|
|
if(key.equals(pairs[i][0]))
|
|
|
|
return (V)pairs[i][1];
|
|
|
|
return null; // Did not find key
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
|
|
for(int i = 0; i < index; i++) {
|
|
|
|
result.append(pairs[i][0].toString());
|
|
|
|
result.append(" : ");
|
|
|
|
result.append(pairs[i][1].toString());
|
|
|
|
if(i < index - 1)
|
|
|
|
result.append("\n");
|
|
|
|
}
|
|
|
|
return result.toString();
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
AssociativeArray<String,String> map =
|
|
|
|
new AssociativeArray<>(6);
|
|
|
|
map.put("sky", "blue");
|
|
|
|
map.put("grass", "green");
|
|
|
|
map.put("ocean", "dancing");
|
|
|
|
map.put("tree", "tall");
|
|
|
|
map.put("earth", "brown");
|
|
|
|
map.put("sun", "warm");
|
|
|
|
try {
|
|
|
|
map.put("extra", "object"); // Past the end
|
|
|
|
} catch(ArrayIndexOutOfBoundsException e) {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Too many objects!");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(map);
|
|
|
|
System.out.println(map.get("ocean"));
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Too many objects!
|
|
|
|
sky : blue
|
|
|
|
grass : green
|
|
|
|
ocean : dancing
|
|
|
|
tree : tall
|
|
|
|
earth : brown
|
|
|
|
sun : warm
|
|
|
|
dancing
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|