When i use this code from another class (I'll post the client if necessary, but in the interest of making a short post:)
I get an ArrayStoreException from line 31.
As I see it: the array is of runtime-type V, the item that should be added to the array should be aswell, or the error should have occured at compiletime, when trying to call pu(K,V) with a wrong value type?
So, what am I not getting? :)
import java.util.Arrays;
public class ResizableMap<K extends Comparable<K>, V> {
private int N=0;
private K[] keys;
private V[] vals;
@SuppressWarnings("unchecked")
public ResizableMap() {
keys = (K[]) new Comparable[1];
vals = (V[]) new Comparable[1];
}
public boolean isEmpty() { return N==0; }
public int size() { return N; }
public void put(K key, V value) {
if(N == keys.length) resize(2*keys.length);
int p = rank(key);
if (key == keys[p]){
vals[p] = value;
return;
}
for(int i=N; i>p; i--) {
keys[i] = keys[i-1];
vals[i] = vals[i-1];
}
keys[p] = key;
vals[p] = value;
N++;
}
public V getValue(K key){
if (isEmpty()) return null;
int i = rank(key);
if (i < N && keys[i].compareTo(key) == 0) return vals[i];
return null;
}
public K getKey(int i){
if (i>=N) throw new ArrayIndexOutOfBoundsException(i);
return keys[i];
}
public int rank(K item){
return rank(item, 0, N-1);
}
public int rank(K item, int lo, int hi) {
if (item == null) return -1;
if (lo > hi) return lo;
int half = lo + (hi-lo)/2;
int cmp = item.compareTo(keys[half]);
if (cmp < 0) return rank(item, lo, half-1);
if (cmp > 0) return rank(item, half +1, hi);
return half;
}
private void resize(int cap) {
@SuppressWarnings("unchecked")
K[] tmpK = (K[]) new Comparable[cap];
@SuppressWarnings("unchecked")
V[] tmpV = (V[]) new Comparable[cap];
for(int i=0; i<N; i++){
tmpK[i] = keys[i];
tmpV[i] = vals[i];
}
keys = tmpK;
vals = tmpV;
}
//A litte test
public static void main(String[] args) {
ResizableMap<Character, Character> rm = new ResizableMap<>();
f
for (int i=33; i<122; i++){
rm.put((char)i, (char)i);
}
}
}