0

Here is some code

package deleteit;
import java.lang.*;
import java.io.*;
import java.util.*;

public class Deleteit {

public static void main(String[] args) throws IOException {

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    ArrayList<Integer> arr1=new ArrayList<Integer>();
    arr1.add(100000);
    arr1.add(1);
    arr1.add(100000);
    arr1.remove(1);
    if(arr1.get(0)==arr1.get(1))
    {
        System.out.println("GUd");
    }
    else
       System.out.println("damnit");

}

}

Now Gud should be printed as 100000 is equal to 100000 as 1 gets removed from the ArrayList so it is left with 100000 and 100000 . So why does damnit gets printed ?

Is that a BUG?

damnitman1
  • 17
  • 6

1 Answers1

2

You have to use equals not ==.

Here is some sample code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class DeleteIt {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<Integer> arr1 = new ArrayList<Integer>();
        arr1.add(100000);
        arr1.add(1);
        arr1.add(100000);
        arr1.remove(1);
        if (arr1.get(0).equals(arr1.get(1))) {
            System.out.println("GUd");
        } else
            System.out.println("damnit");
    }
}

Number objects (Integer, Double, Short) should always be compared with .equals and not ==. The same applies to String, by the way.

If you use == you are comparing references and not the actual values.

By the way, regarding unboxing and using the == sign. If you apply intValue() on the first value of the comparison, you will be able to use the == sign. So this code will also work:

package stackoverflow;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class DeleteIt {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<Integer> arr1 = new ArrayList<Integer>();
        arr1.add(100000);
        arr1.add(1);
        arr1.add(100000);
        arr1.remove(1);
        if (arr1.get(0).intValue() == arr1.get(1)) {
            System.out.println("GUd");
        } else
            System.out.println("damnit");

    }

}

This latter code seems to force unboxing and then the == is not comparing references, but actual values.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76