Java Long/Integer polymorpherism using operators >, <, ==

In this forum members can discuss topics about specific programming languages.
Post Reply
User avatar
Posts: 60
Joined: Mon Jun 10, 2013 6:31 am

Java Long/Integer polymorpherism using operators >, <, ==

Post by RishadanPort » Wed Jun 19, 2013 1:49 pm


I have a function:

static <E extends Comparable<E>> void foo(List<E> a)

that takes in a List of of a comparable object in Java.

It later does this operation:
if(a.get(location1).compareTo(a.get(locations2)) == -1)

to check if a[location1] < a[location2]

I am wondering if there is a way to actually do this using operators: "<, >, ==, ... " etc instead of the functions as it gets a bit messy when doing it.
I know that in C++, you can overload these operators.


Rishada is the gateway to free trade—but the key will cost you.

Posts: 356
Joined: Sun Mar 27, 2011 9:01 am

Re: Java Long/Integer polymorpherism using operators >, <,

Post by thundre » Wed Jun 19, 2013 2:15 pm

No, you can't overload comparison operators in Java.

In particular, the == operator already has a meaning for generic Objects. It checks whether the references are equal, so "abc" == "abc" might be true or false depending on whether your compiler optimizes the two constant strings into a single reference or not.

You can do what you want if you declare the objects Long or Integer first. Then they will be converted to primitive long or int for the comparison. If you want to use both, you'll need to duplicate each method.

Post Reply