Chapter 17 - Exercise 12

(1) Substitute a HashMap, a TreeMap and a LinkedHashMap in AssociativeArray .Java’s main( ).




package com.ciaoshen.thinkinjava.chapter17;
import java.util.*;

class AssociativeArray<K,V> {
    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
    }
    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 class Exercise12{

    public static void test(Map<String,String> map){
        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) {
            System.out.println("Too many objects!");
        }
        System.out.println(map);
        System.out.println(map.get("ocean"));
    }

    public static void main(String[] args){
        //AssociativeArray<String,String> map1 = new AssociativeArray<String,String>(6);
        HashMap<String,String> map2=new HashMap<String,String>();
        TreeMap<String,String> map3=new TreeMap<String,String>();
        LinkedHashMap<String,String> map4=new LinkedHashMap<String,String>();

        Exercise12.test(map2);
        Exercise12.test(map3);
        Exercise12.test(map4);
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.