2011-12-03 22 views
0
map<string, pair<int, int> > common;  
map<string, pair<int, int> >::iterator cIter = common.find(code); 
     if(cIter == common.end()) 
     { 
      pair<int, int> values(1, count); 
      common.insert(make_pair(code, values)); 
     } 
     else 
      cIter->second.first++; 

任何人都可以幫助我將上面的代碼轉換爲Java?C++ Map和Java Entry

private java.util.HashMap<String, Entry<Integer, Integer>> common = new java.util.HashMap<String, Entry<Integer, Integer>>(); 
Entry<Integer, Integer> cIter = common.get(code); 
      if (cIter == common.) { 
       Entry<Integer, Integer> values = new AbstractMap.SimpleEntry<Integer, Integer>(1, count); 
       common.put(code, values); 
      } else { 
       cIter.second.first++; 
      } 

這是我試過的第二種方法getValues()和第一種方法getKey()?

+0

第一個代碼是什麼語言?它*看起來像Java,但它看起來像C++。 –

+0

C++對不起,我認爲我發佈了錯誤的代碼,我試圖轉換下面的代碼是我試圖轉換爲Java – user236501

回答

0

Java沒有Pair tuple類,我不確定使用Entry是最好的選擇,因爲您需要更新Entry的「關鍵」。

相反,你應該創建一個類來做到這一點。

class Counters { 
    int counter1; // use meaningful names here 
    final counter2; 
    public Counters(counter1, counter2) { this.counter1 = counter1; this.counter2 = counter2; } 
} 

Map<String, Counters> common = new HashMap<>(); 

Counters counters = common.get(code); 
if (counters == null) 
    common.put(code, counters = new Counters(1, count)); 
else 
    counters.counter2++; 

如果(itr.second.first>最大){最大= itr.second.first; minCount = itr.second.second; code = itr.next()。getKey(); }

if(counters.counter1 > max) { 
    max = counters.counter1; 
    minCount = counters.counter2; 
    code = null; // isn't needed AFAIK. 
} 
+0

嗨,謝謝,我得到了另一個代碼:我非常困惑與第一和第二,這是getValue或getKey或counter1和counter2?你能幫我嗎?如果(itr.second.first> max){max = itr.second.first; minCount = itr.second.second;代碼= itr.next()。getKey(); } – user236501

+0

'我對第一和第二'很困惑,這是Java沒有Pair的原因之一。 ;) –

+0

Oic謝謝,所以你的counter2實際上是指值的權利?而對於C++對,第一次實際上是指鍵和第二個指的是我是對的值? – user236501

0

如果地圖不包含密鑰,則Java的Hashmap get函數將返回null。這似乎是你的Java代碼上面的差距。請參閱: http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

請注意,有些人建議使用小類,而不是嘗試使用像Entry這樣的通用結構(實際上是爲了表示Map中的鍵/值對)。請參閱:What is the equivalent of the C++ Pair<L,R> in Java?

+0

這是什麼意思cIter-> second.first ++; – user236501

+0

如果你正在重用Entry類,那麼我猜它會是get/setValue。請參閱:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Map.Entry.html。從上面的Stackoverflow鏈接或者你自己的類,而不是Entry類使用一對類可能會更好,因爲它看起來不像語義是正確的。 –