我实质上是在创建自己的Dictionary类,在其中它可以作为堆栈使用。我可以将键值对(我自己创建的另一个类)放入字典中,将其保存在数组中。当我通过逐行纠正对put()的每次调用来手动放置键值对时,它可以正常工作。但是,当我使用for循环时,它无法正常工作。如果我检查字典中是否有键,则使用for循环创建的字典将返回false,而使用另一个则返回true。两个字典都使用我创建的方法打印出完全相同的东西。但是,使用for循环创建的字典在使用方法时无法提供正确的输出。
这是主要代码:
有人知道为什么两个字典不同吗?
编辑:我对put()的代码如下
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 +"]}";
}
}
配对是我创建的另一个类,仅表示一个键值对。
答案 0 :(得分:0)
好,我只重复你的问题。
词典:
public class Dictionary {
Map<String, Integer> map = new HashMap<>();
public boolean contains(String key) {
for(String mapKey : map.keySet()) {
if(mapKey == key) {
return true;
}
}
return false;
}
}
主要:
public static void main(String[] args) {
Dictionary dict = new Dictionary();
dict.map.put("X" + 0, 0);
dict.map.put("X" + 1, 1);
dict.map.put("X" + 2, 2);
dict.map.put("X" + 3, 3);
System.out.println(dict.contains("X2")); // true
Dictionary dict2 = new Dictionary();
for(int i=0; i<4; i++) {
dict2.map.put("X" + i, i);
}
System.out.println(dict2.contains("X2")); // false
}
存在问题是因为我使用==而不是equals方法比较字符串值,所以我几乎可以肯定您也会犯同样的错误。您必须使用equals方法比较字符串,否则可能会遇到类似的奇怪情况