Preface
I'm trying to implement a Dictionary data structure that stores Pairs(an object) in a dynamic array.
The array starts off with size [10]. Every time the user tries to add another Pair to the Dictionary when the array is full; the dynamic array increments the length of the array by 5.
There are 3 relevant methods.
put: Adds a pair to the dynamic array
dynamicArray: Increases the size of the array when full
get: Retrieves a specific element from the array
Problem
When the dynamicArray is called to be initialized with many elements, the elements don't seem to be properly stored. When trying to get the elements, it catches a NoSuchElementException which indicates the values were not stored in the first place. Here is the relevant code, thank you.
public Token get (String key) throws NoSuchElementException,
NullPointerException{
boolean found=false; //Represents if pair is found
Token token = null;
if (key ==null)
throw new NullPointerException ();
for (int i=array.length-1; i>=0; i--){
if ( array[i]!=null && array[i].getKey() == key){
found=true;
return (array[i]).getToken();
}
}
if (found!=true)
throw new NoSuchElementException ();
return token;
}
private void dynamicArray(){
if (array[array.length-1]!=null){
Pair[]replace = new Pair[array.length+5];
System.arraycopy(array, 0, replace, 0, array.length);
array=replace;
}
}
public void put (String key, Token value) throws NullPointerException{
if (key == null || value == null)
throw new NullPointerException ();
dynamicArray();
Pair p1 = new Pair (key,value);
for (int i=0; i<array.length; i++){
if (array[i]== null ){
dynamicArray();
array[i]=p1;
break;
}
}
}
TestCase
@Test()
public void testPutDyncamicArray() {
System.out.println("test: testPutDyncamicArray");
Dictionary dict = new Dictionary();
for (int i = 0; i < 1000; i++) {
dict.put("X" + i, new Token(i));
}
for (int i = 0; i < 1000; i++) {
Assert.assertEquals(new Token(i), dict.get("X" + i));
}
}