Chris Headleand Chris Headleand - 3 months ago 20
Java Question

Is it possible to find out if a value exists twice in an arraylist?

I have an integer arraylist..

ArrayList <Integer> portList = new ArrayList();


I need to check if a specific integer has already been entered twice. Is this possible in Java?

Answer

I know it's an old question, but since I was here looking for the answer, I thought I'd share MY solution

public static boolean moreThanOnce(ArrayList<Integer> list, int searched) {

    int numCount = 0;
    boolean more = false;

    for (int thisNum : list) {
        if (thisNum == searched) {
            numCount ++ ;
        }
    }

    if (numCount > 1) {
        more = true;
    }

    return more;
}