在ArrayList中检查-1值时,Collections.frequency返回0

时间:2013-12-20 13:33:34

标签: java collections

List line = [0, -1, 28, 0, 50, 0, -1, 75, 0] // pseudocode
System.out.println(Collections.frequency(line, -1));

为什么Collections.frequency在检查0值时会返回-1

3 个答案:

答案 0 :(得分:2)

这就是collections.frequency的工作原理:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class stackexample {
    public static void main(String[] args) {
        List<Integer> values = Arrays.asList( 5, 0, 0, 2 );
        int occurrences = Collections.frequency(values, 0);
        System.out.println("occurrences of zero is " + occurrences); //shows 0 but answer should be 2
    }
}

在您的情况下,它返回零,因为您的收藏中没有-1

答案 1 :(得分:1)

line中没有值为-1的项目。

答案 2 :(得分:0)

根据java docs

Returns the number of elements in the specified collection equal to the specified object.     
More formally, returns the number of elements e in the collection such that (o == null ? e
== null : o.equals(e)).

所以没有匹配所以返回0见下文

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#frequency(java.util.Collection,java.lang.Object)