Java Collections帮助(Practice-It!)

时间:2013-08-15 07:43:24

标签: java facebook list collections maps

我需要以下问题的帮助:http://practiceit.cs.washington.edu/problem.jsp?category=Building+Java+Programs%2C+3rd+edition%2FBJP3+Chapter+11&problem=bjp3-11-e19-rarest

这是我的代码:

public static int rarest(Map<String, Integer> m) {
if ( m.isEmpty() ) {
    throw new NullPointerException();
}

int min = Integer.MAX_VALUE;
int store = Integer.MAX_VALUE;
Map<Integer, Integer> m1 = new TreeMap<Integer, Integer>();
List<Integer> l = new ArrayList<Integer>();

for (Integer a: m.values()) {
    l.add(a);
}

for(int i=0; i<l.size(); i++) {
    int temp = 1;
    for(int j=i+1; j<l.size(); j++) {
        if ( l.get(i) == l.get(j) ) {
            temp++;
        }
    }

    if ( !m1.containsKey(l.get(i)) ) {
        m1.put( l.get(i), temp );
    }
}

for(Integer a: m1.keySet()) {
    int val = m1.get(a);
    if (val == min) {
        if ( a<store ) {
            store = a;
        }
    } else if ( val < min ) {
        min = val;
        store = a;
    }
}

return store;

}

当代码运行时:

{A=1000, B=1, C=101, D=3, J=1000, K=101, L=3, LN=1, M=1000, N=101, R=3, S=1000, T=101, V=3, W=1, X=1, Y=1, Z=1}, 

我返回1000,返回时应为3。为什么会这样?

1 个答案:

答案 0 :(得分:1)

你应该改变

l.get(i) == l.get(j)

l.get(i).equals(l.get(j)
  • Integer是参考类型
  • equals()比较值
  • ==比较指针