

Don't judge an Integer by its wrapper. - jjcm
http://www.cmsimike.com/blog/2010/08/17/dont-judge-an-integer-by-its-wrapper/

======
heresy
I'm sure someone can come up with a justification for this, but coming at this
from a C# background, why is this desirable?

Now you have to carry around the fact that == sometimes isn't a reference
comparison, even though that's what Java claims it always is?

Seems like a pretty poor design decision.

If I'm missing something basic, please correct away.

~~~
ks
Unlike C# (I think), there's a difference between "int" and "Integer. Integer
is a class, while "int" is a primitive. Due to auto-boxing you can create an
Integer object from an int, but it will still remain an object.

The problem is caused by him comparing objects as if they were primitives. The
Integer class is basically just a wrapper around an "int" primitive. When an
Integer object is initialized with a value between -128 and 127 it will return
an object from an internal cache.

The second time he creates an Integer with the value of 127 it uses the cached
object, which of course is identical to the previous one. When he tries this
with 128, the cache is not used and a new Integer object is created.

tl;dr; Integer is an object where some values are cached to avoid creating a
new object. The "==" operator compares the objects, and not the values they
represent.

~~~
heresy
It's the same in C#, == is used for reference comparison, you use it when you
want to know whether two objects are the same object, whereas you would
typically use .Equals() for value comparison.

There is no wrapper class for "primitives" in C# though, to box it, you cast
it to System.Object, and that allocates an object instance for you on the
heap. To unbox, cast it to System.Int32.

'int' in C# is just an alias for System.Int32 though, so I guess there is no
analogue to the Java situation in C#. You'd either be comparing System.Object
references, or System.Int32 value types, not some hybrid.

Example:

    
    
      using System;
      class Boxing
      {
        static void Main(string[] args)
        {
            int i1 = 5;
    
            object o1 = 5;
            object o2 = 5;
            
            int i2 = (int)o2;
            
            Console.WriteLine("o1 == o2: {0}", o1 == o2);
            Console.WriteLine("i1.Equals(o1): {0}", i1.Equals(o1));
            Console.WriteLine("i2: {0}", i2);
        }
      }
    

Prints:

    
    
      o1 == o2: False
      i1.Equals(o1): True
      i2: 5

