|
| 1 | +package btp.oneP; |
| 2 | + |
| 3 | +public class AssociativeArray<K,V>{ |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + AssociativeArray<String,String> map = new AssociativeArray<String,String>(6); |
| 7 | + map.put("sky", "blue"); |
| 8 | + map.put("grass", "green"); |
| 9 | + map.put("ocean", "dancing"); |
| 10 | + map.put("tree", "tall"); |
| 11 | + map.put("earth", "brown"); |
| 12 | + map.put("sun", "warm"); |
| 13 | + try{ |
| 14 | + map.put("extra", "object"); |
| 15 | + }catch(Exception e){ |
| 16 | + System.out.println(e); |
| 17 | + } |
| 18 | + System.out.println(map); |
| 19 | + System.out.println(map.get("ocean")); |
| 20 | + } |
| 21 | + |
| 22 | + private Object[][] pair; |
| 23 | + private int index; |
| 24 | + public AssociativeArray(int length){ |
| 25 | + pair = new Object[length][2]; |
| 26 | + } |
| 27 | + |
| 28 | + public void put(K key,V value){ |
| 29 | + if(index >= pair.length){ |
| 30 | + throw new ArrayIndexOutOfBoundsException(); |
| 31 | + } |
| 32 | + pair[index++] = new Object[]{key,value}; |
| 33 | + } |
| 34 | + |
| 35 | + @SuppressWarnings("unchecked") |
| 36 | + public V get(K key){ |
| 37 | + for(int i=0;i<pair.length;i++){ |
| 38 | + if(key.equals(pair[i][0])){ |
| 39 | + return (V)pair[i][1]; |
| 40 | + } |
| 41 | + } |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + public String toString(){ |
| 46 | + StringBuilder sb = new StringBuilder(); |
| 47 | + for(int i=0;i<index;i++){ |
| 48 | + sb.append(pair[i][0].toString()); |
| 49 | + sb.append(" : "); |
| 50 | + sb.append(pair[i][1].toString()); |
| 51 | + if(i<index-1){ |
| 52 | + sb.append("\n"); |
| 53 | + } |
| 54 | + } |
| 55 | + return sb.toString(); |
| 56 | + } |
| 57 | +} |
0 commit comments