I am essentially creating my own Dictionary class where it works as a stack. I can put key-value pairs (another class i created myself) into my dictionary which holds them in an array. When I manually put the key-value pairs by righting each call to put() line by line it works fine. But when i use a for loop it does not work properly. If i check to see if a key is in my dictionary it returns false with the dictionary created with the for loop and true with the other one. Both dictionaries print the exact same thing with the method i created. But the dictionary created with the for loop does not gives correct outputs when methods are used.
here is the code for the main :
Does anyone know why the two dictionaries are different?
Edit : my code for put() is as follows
public class Dictionary implements Map<String, Integer> {
private final static int INITIAL_CAPACITY = 10;
private final static int INCREMENT = 5;
private int count;
Pair[] elems;
public int getCount() {
return count;
}
public int getCapacity() {
return elems.length;
}
public Dictionary() {
elems = new Pair[INITIAL_CAPACITY];
count = 0;
}
@Override
public void put(String key, Integer value) {
Pair elem = new Pair(key, value);
elems[count] = elem;
count++;
if (count == elems.length) {
increaseCapacity();
}
}
private void increaseCapacity() {
Pair[] newElems = new Pair[count + INCREMENT];
for (int i = 0; i < count; i++) {
newElems[i] = elems[i];
}
elems = newElems;
}
@Override
public boolean contains(String key) {
for (int i = 0; i < count; i++) {
if (elems[i].getKey() == key) {
return true;
}
}
return false;
}
@Override
public Integer get(String key) {
boolean got = false;
Integer value = 0;
for (int i = count - 1; i > - 1; i--) {
if (elems[i].getKey() == key && !got) {
value = elems[i].getValue();
got = true;
}
}
return value;
}
@Override
public void replace(String key, Integer value) {
Pair newPair;
for (int i = count - 1; i > - 1; i--) {
if (elems[i].getKey() == key) {
newPair = new Pair(key, value);
elems[i] = newPair;
}
}
}
@Override
public Integer remove(String key) {
Integer saved = null;
boolean removed = false;
for (int i = count - 1; i > - 1; i--) {
if (elems[i].getKey() == key && !removed) {
removed = true;
saved = elems[i].getValue();
elems[i] = null;
}
}
return saved;
}
@Override
public String toString() {
String res;
res = "Dictionary: {elems = [";
for (int i = count-1; i >= 0 ; i--) {
res += elems[i];
if (i > 0) {
res += ", ";
}
}
return res +"]}";
}
}
Pair is another class I have created that just represents a key-value pair.