तो मेरे पास एक बहुत ही अजीब बग है। जब मैं मूल रूप से एक बड़े ट्रीमैप की पहली 10 कुंजी पर फिर से शुरू करने के लिए एक कुंजीसेट() का उपयोग कर रहा था, तो मैं उस पर ठोकर खाई। चाबियों में से एक शून्य वापस लौट रहा था, जहां तक मेरी समझ पूरी हो सकती है। तो मैं नीचे परीक्षण कोड लिखा है:ट्री मैप में कुंजी शून्य लौट रहा है
int i = 0;
for (Map.Entry<String, Integer> es : sortedMap.entrySet()){
if (i >= 10) {
break;
}
if (sortedMap.containsKey(es.getKey())){
System.out.println(es.getKey() + ":" + sortedMap.get(es.getKey()));
} else {
System.out.println("Key " + es.getKey() + " does not exist, yet...");
System.out.println("This does work: " + es.getKey() + ":" + es.getValue());
System.out.println("This does NOT work: " + es.getKey() + ":" + sortedMap.get(es.getKey()));
}
i++;
}
और मिल निम्न परिणाम:
SOAP:967
'excerpt'::679
'type'::679
Key 'author_url': does not exist, yet...
This does work: 'author_url'::679
This does NOT work: 'author_url'::null
'date'::679
Android:437
TLS:295
message:283
server:230
monthly:215
<<<<<<<<<<<<<<<<<<<<DUMPING MAP!
{SOAP=967, 'excerpt':=679, 'type':=679, 'author_url':=679, 'date':=679, Android=437, TLS=295, message=283, server=230, monthly=215...
मैं शीर्ष दस के बाद नक्शा काट के रूप में वहाँ है वहाँ में एक बहुत अधिक है, लेकिन यह के सभी एक मूल्य के साथ एक कुंजी है।
तो मेरा सवाल यह है: ट्रीमैप से सीधे (कुंजी) प्राप्त करने के लिए कुंजी का उपयोग करते समय मुझे शून्य क्यों मिल रहा है, लेकिन EntrySet सही कुंजी और मान देता है?
यहाँ मेरी तुलनित्र के बाद से मैं पूर्णांक पर आदेश देने से कर रहा हूँ:
class ValueComparator implements Comparator<Object> {
Map<String, Integer> base;
public ValueComparator(Map<String, Integer> base) {
this.base = base;
}
public int compare(Object a, Object b) {
if ((Integer) base.get(a) < (Integer) base.get(b)) {
return 1;
} else if ((Integer) base.get(a) == (Integer) base.get(b)) {
return 0;
} else {
return -1;
}
}
}
और ट्री-मैप निम्नलिखित के रूप में बनाया गया है:
ValueComparator bvc = new ValueComparator(allMatches);
TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>(bvc);
//Sort the HashMap
sortedMap.putAll(allMatches);
कहाँ allMatches एक HashMap<String, Integer>
आप ट्री-मैप के लिए एक असामान्य तुलनित्र का उपयोग कर रहे हैं? यदि हां, तो क्या हम इसका कोड देख सकते हैं? यह आपके डंप से दिखता है जैसे कि आप डिफ़ॉल्ट 'स्ट्रिंग' ऑर्डरिंग का उपयोग नहीं कर रहे हैं ... –
@LouisWasserman मेरे तुलनित्र को जोड़ा गया। –
आपके पास उस कक्षा में एक निर्माता और सदस्य क्यों है? तुलनित्र को सामान्य रूप से प्रत्येक तत्व के लिए बुलाया जाता है ताकि आपको परिणामस्वरूप मानचित्र का संदर्भ नहीं देना चाहिए। आपका पूरा कोड उपयोगी होगा। – tom