Weird Integer boxing in Java

前端 未结 12 2086
广开言路
广开言路 2020-11-22 00:15

I just saw code similar to this:

public class Scratch
{
    public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;
        System.o         


        
12条回答
  •  日久生厌
    2020-11-22 00:37

    That is an interesting point. In the book Effective Java suggests always to override equals for your own classes. Also that, to check equality for two object instances of a java class always use the equals method.

    public class Scratch
    {
        public static void main(String[] args)
        {
            Integer a = 1000, b = 1000;
            System.out.println(a.equals(b));
    
            Integer c = 100, d = 100;
            System.out.println(c.equals(d));
        }
    }
    

    returns:

    true
    true
    

提交回复
热议问题