-1

I have a Pair class of Generic Type and the following way of subtraction gives me error as the operator - is not defined for T,T. I searched and found that link. I wonder it is the only way of operator overloading in Java. I think not straightforward. I came from C++ background. Thanks

public class Pair<T>{


    private T first;
    private T second;

    public T firstpairSub(Pair<T> s) {
        return this.first - s.first;
    }
}
Community
  • 1
  • 1
batuman
  • 7,066
  • 26
  • 107
  • 229
  • If you really want to do this, you could use Scala, which, in the end, compiles to java – Mirco Mar 05 '14 at 08:00
  • Besides that operator overloading is not possible in Java, as you don't even make any assumptions about `T`, this is simply wrong, because anyone could extend your class with type `Object`, `String` or `List`. – Smutje Mar 05 '14 at 08:00
  • Java generics do not work in the same way as C++ templates. Generics are not a template from which different implementations are generated, like in C++. You'll need to unlearn thinking about generics as if they are templates. – Jesper Mar 05 '14 at 08:00
  • possible duplicate of [Operator overloading in Java](http://stackoverflow.com/questions/1686699/operator-overloading-in-java) – Jason C Mar 05 '14 at 08:02
  • If overloading is not allowed in Java, why Generic type is allowed in Java. Quiet frustrating – batuman Mar 05 '14 at 08:06
  • I know a lot of people discussed. But I like to have a discussion to convince myself. – batuman Mar 05 '14 at 08:19

2 Answers2

0

You cannot overload operators in Java.

The subtraction operator is only defined for numeric types.

What would you expect that to produce for, say, a Pair<String>? What about a Pair<Socket> or a Pair<java.sql.Driver>?

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • Yes if you have to use two Sockets for your application, you can wrap it in a pair and it makes Socket1 and Socket2. It makes sense to me. – batuman Mar 05 '14 at 08:21
  • 1
    His point is, that your method firstPairSub would fail, if the Pair was of type Socket. – LuigiEdlCarno Mar 05 '14 at 08:43
0

You could simply do the conversion yourself:

public class Pair<T extends Number>{

...

public T firstpairSub(Pair<T> s) throws Exception{
    if(this.first instanceof Integer && s.first instanceof Integer)
        return (Number) ((Integer)this.first- (Integer)s.first);
    if(this.first instanceof Double && s.first instanceof Double)
    ...

    throw new Exception("Invalid type")

}
LuigiEdlCarno
  • 2,410
  • 2
  • 21
  • 37
  • So what is the point of Making Generic T if I have to use instanceof. I'll have a lot of instanceof. – batuman Mar 05 '14 at 08:20