Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for zero in Java ArrayList using contains()

I have this code snippet that is basically checking for a 0 value in a ArrayList of long integers.

import java.io.*;
import java.util.*;

class main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        long zero = 0;

        ArrayList<Long> alist = new ArrayList();        
        alist.add (zero);

        if (alist.contains(0))
            System.out.println ("contains zero");
        else
            System.out.println ("contains no zero");
    }
}

and the output I get is contains no zero. Rather unnerving! Is this a bug or the expected behavior?

like image 397
lifebalance Avatar asked Dec 25 '22 22:12

lifebalance


1 Answers

Change this logical check to: alist.contains(0L). This behavior is related to auto boxing/unboxing. int is boxed to Integer, and long is boxed to Long. In your list you put a long (boxed to a Long), then you search for an int (boxed to an Integer)... so you don't find it.

like image 78
peter.petrov Avatar answered Jan 20 '23 22:01

peter.petrov