是否有可能在arraylist中找出值是否存在两次?

Chr*_*and 3 java arraylist

我有一个整数arraylist ..

ArrayList <Integer> portList = new ArrayList();
Run Code Online (Sandbox Code Playgroud)

我需要检查是否已经输入了两次特定的整数.这在Java中可行吗?

Sur*_*vor 12

您可以使用这样的内容来查看特定值的次数:

System.out.println(Collections.frequency(portList, 1));
// there can be whatever Integer, i put 1 so you can understand
Run Code Online (Sandbox Code Playgroud)

并且要检查特定值是否存在多次,您可以使用以下内容:

if ( (Collections.frequency(portList, x)) > 1 ){
    System.out.println(x + " is in portList more than once ");
} 
Run Code Online (Sandbox Code Playgroud)


use*_*146 5

我的解决方案

public static boolean moreThanOnce(ArrayList<Integer> list, int searched) 
{
    int numCount = 0;

    for (int thisNum : list) {
        if (thisNum == searched) 
            numCount++;
    }
    
    return numCount > 1;
}
Run Code Online (Sandbox Code Playgroud)