In Java, is there some way to make things that only accept ints accept doubles without conversion?

2017-10-22 7:39 am
I'm trying to get a bunch of methods that only take ints to take doubles (I can't change all the methods directly), and I'm trying to get them to accept doubles but I'm wondering if there's some way to do this without having to convert the doubles to ints. I'm afraid that if I do convert them to ints, it'll cause errors down the line.

回答 (1)

2017-10-22 9:31 am
✔ 最佳答案
No. The compiled byte code for those methods will expect actual primitive int values.

You could overload those methods, making copies that accept double or float arguments. That could work for static methods but is unlikely to work well with instance methods. Your copies would have to be changed every time the original int methods changed, though, so I d look at least twice for another solution before creating a dual maintenance situation.

Java generics won t help, either--not if you do any arithmetic or comparisons. You can t "unbox" a generic wrapper back into an unknown primitive type.


收錄日期: 2021-05-01 21:58:51
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20171021233903AAMlraq

檢視 Wayback Machine 備份