c++映射和Java入口

C++ Map and Java Entry

本文关键字:入口 Java 映射 c++      更新时间:2023-10-16
  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?

 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()?

Java没有Pair元组类,我不确定在这种情况下使用Entry是最好的选择,因为你需要更新Entry的"key"。

你应该创建一个类来做这些。

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

。第一个> max) {max = 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.
}

如果map不包含键,Java的Hashmap get函数将返回null。这似乎是你上面的java代码的差距。看到的:http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

请注意,有些人建议使用一个小的类,而不是尝试使用一个通用的结构,如Entry(它实际上是用来表示Map中的键/值对)。参见:c++的Pair<L,R>在Java中?