java - 是否可以在不更改方法主体的情况下编译通用可变参数方法?
问题描述
考虑这种通用交换方法:
package chapter06;
public class Ex05VarargsSwap {
public static <T> T[] swap (int i, int j, T... values) {
T temp = values[i];
values[i] = values[j];
values[j] = temp;
return values;
}
public static void main(String[] args) {
Double[] result = Ex05VarargsSwap.swap(0,1, 1.5,2,3);
/* The Error: Type mismatch: cannot convert from
* Number&Comparable<?>&Constable&ConstantDesc[] to Double[]
*/
Double[] result2 = Ex05VarargsSwap.<Double>swap(0,1,1.5,2,3);
/* The parameterized method <Double>swap(int, int, Double...) of type Ex05VarargsSwap is not
* applicable for the arguments (int, int, Double, Integer, Integer)
*/
}
}
有没有办法让这段代码在不改变方法的情况下编译?
当然调用:Double[] result3 = Ex05VarargsSwap.swap(0, 1, 1.5, 2.0, 3.0);
编译。
但我希望在不更改参数类型的情况下编译调用。(也许带有注释,或铸造......等)
解决方案
T...
的意思array of T
,同T[]
。你不能有两种类型。在您的示例中,您尝试放入整数和双精度数,您不能T
同时是整数和双精度数
你需要给出一个双打列表,所以不会这样做2
,3
你需要使用2d
and 3d
or or 2.0
and3.0
像这样:
public static void main(String[] args) {
Double[] result = Ex05VarargsSwap.<Double>swap(0, 1, 1.5, 2d, 3d);
}
推荐阅读
- google-apps-script - Gsheets Apps 脚本:在 Google Drive 的特定文件夹中制作电子表格的副本
- python - 在 Python 3.6 中从 CSV 绘制纬度经度
- r - 管道进入 rcorr
- java - 使用在 Java 流中发送电子邮件的地图函数是“糟糕的形式”吗?
- vim - 为什么 SHIFT+V (VISUAL LINE) 不像 CTRL+V (VISUAL BLOCK) 那样插入多行?
- python - 计数输出
- r - 如何使用 usmap 包将状态变量转换为 FIPS 代码?
- api - YouTube 网络请求奇怪的行为
- java - 为什么由于以下 Java 代码,表中的数据会更新为 null?
- angular - 如何测试是否在 jasmin 中触发了 console.error