Java and C++, hmmm…

Java can’t do:

  • Operator overloading
  • Template class
  • Multiple inheritance
  • Pointers — at least not explicitly
  • Multiple classes in a single file — unless only used by the classes in that .java source file

An unfortunate, in my opinion, consequence of not being able to overload operators is the == operator function with objects. This operator only compares instances of objects as opposed to the content of those objects. Which is confusing in light of the primitive int and Java object Integer class, for example.

So when you write:

Java
int i1 = 10;
int i2 = 10;

if (i1 == i2)
    System.out.println("i1 is equal to i2");
else
    System.out.println("i1 is not equal to i2");

Everything works as I would expect: the output is that i1 is equal to i2.

And when you write:

Java
Integer i1 = 10;
Integer i2 = 10;

if (i1 == i2)
    System.out.println("i1 is equal to i2");
else
    System.out.println("i1 is not equal to i2");

The output is also as I would expect: i1 is equal to i2.

But, when you write this:

Java
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);

if (i1 == i2)
    System.out.println("i1 is equal to i2");
else
    System.out.println("i1 is not equal to i2");

You get: i1 is not equal to i2.

So you actually want to compare them like this:

Java
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);

if (i1.equals(i2))
    System.out.println("i1 is equal to i2");
else
    System.out.println("i1 is not equal to i2");

Then you get: i1 is equal to i2.

THIS IS NOT INTUITIVE!

Additionally, it’s confusing because, the primitive int, not being an object, has no equals member function, so only the operator == can even be used when dealing with primitives.

Why not make the .equals function be used for comparison of object instances instead?

When would this ever come up?

Well, it came up for me when I needed to create a Long from an int or Integer. Unfortunately, you can’t just type cast like you normally would:

Java
int i1 = 10;
Long l1 = (Long)i1;

This doesn’t work. So you actually have to either create a new Long object like this:

Java
int i1 = 10;
Long l1 = new Long(i1);

However, the Long constructor, and other wrapper objects around primitive types, has been deprecated since Java 9.

Or you can type cast the int to long and create a Long object from the result:

Java
int i1 = 10;
Long l1 = (long)i1;

If you have an Integer object you can use Integer.longValue():

Java
Integer i1 = 10;
Long l1 = i1.longValue();

All these have the result that the == and .equals both function the same way. The only case that is problematic is using the constructor.


by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *