Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

how to use generics in Java with language operators and generic class extending Number

I would like to perform an operation on two generics argument of the same type both extending Number.

Is it Possible? I always used to call methods on generic arguments, but seems there is some problem using operators (The operator + is undefined for the argument type(s) T, T).

public static <T extends Number> T sum(T a, T b){
    return a+ b;
}

What am I doing wrong?

EDIT: I try to improve a little bit my question. I understood that operators are not defined for type Number. It's a bit sad this thing because it would be nice to perform such an operation without introducing new interfaces like suggested by @Victor Sorokin.

But I still don't understand one thing: if operators are not implemented in the class Number, then at least in Double class should be implemented because I can use + operator with double. Neither these line of code will compile:

public static <T extends Double> T sum(T a, T b){

    T c = a +b;
}

why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's not possible because Number doesn't have a + operator associated with it. In particular, you can't do this:

Number a = new Integer(1);
Number b = new Integer(2);
Number c = a + b;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...