当我尝试从Map获取值时遇到了问题。这是详细信息。
我宣布了这个结构:
Map<String, Map<String, IrregularWord>> result4 = new TreeMap<>();
作为键,我使用2_5_1
,3_5_1
,21_4_2
等字符串。当我填充result4
时,我得到了这个结果。< / p>
然后我尝试读取result4
中的所有值,然后使用它们:
for (String key : result4.keySet()) {
Map<String, IrregularWord> words = result4.get(key);
// other code
}
当key == 2_5_1
words.size() == 14
{9}} {9}} {9}} result4
时,我9
{9}}。{/}
更新:此示例的正确值为{{1}}。
我的问题是为什么我的结果不正确?也许Map的哈希算法存在问题?
感谢您的帮助。
答案 0 :(得分:0)
我不知道为什么,但是我自己Comparator
的所有问题都没有写在这里,这是我的错误。
所以,我真的用过了
Map<String, Map<String, IrregularWord>> result4 = new TreeMap<>(new LessonsShortPathComparator());
Comparator
:
public class LessonsShortPathComparator implements Comparator<String> {
public static String LES_SHORT_PATH_REG_EXP = "[0-9]+_[0-9]+_[0-9]+";
public int compare(String o1, String o2) {
String[] o1Str = o1.split("_");
String[] o2Str = o2.split("_");
if (Integer.parseInt(o1Str[0]) > Integer.parseInt(o2Str[0]))
return 1;
if (Integer.parseInt(o1Str[1]) > Integer.parseInt(o2Str[1]))
return 1;
if (Integer.parseInt(o1Str[2]) > Integer.parseInt(o2Str[2]))
return 1;
return 0;
} else
return o1.compareTo(o2);
}
}
这是一个问题。我只是为了更大的价值,但不包括更少的价值。当我这样解决时:
public class LessonsShortPathComparator implements Comparator<String> {
public static String LES_SHORT_PATH_REG_EXP = "[0-9]+_[0-9]+_[0-9]+";
public int compare(String o1, String o2) {
if (o1.matches(LES_SHORT_PATH_REG_EXP) && o2.matches(LES_SHORT_PATH_REG_EXP)) {
String[] o1Str = o1.split("_");
String[] o2Str = o2.split("_");
for (int i = 0; i < o1Str.length; i++) {
int i1 = Integer.parseInt(o1Str[i]);
int i2 = Integer.parseInt(o2Str[i]);
if (i1 - i2 != 0) {
return i1 - i2;
}
}
return 0;
} else
return o1.compareTo(o2);
}
}
现在一切正常。我不明白为什么?在IrregularWord
之后,Comparator
的链接可能会变得糟糕。所有TreeMap
的Firs比较键并找到正确的值位置,但反之亦然。
抱歉说明不完整。我真的不知道Comparator
会影响到这一点。