【发布时间】:2014-03-01 19:55:01
【问题描述】:
我得到了这个 ArrayTools 类,它对一个整数数组执行许多数组操作。
public class ArrayTools {
private int arr[];
/* other variables */
public ArrayTools(int max) {
arr = new int[max];
/* other stuff */
}
目前该类的所有方法都使用该整数数组。
现在我需要为浮点数组实现完全相同的方法。我显然不想将整个代码 c&p 到一个新的 ArrayToolsFloat 类中,将“int”更改为“float”,这是它们之间的唯一区别。 我想“正确”的方法是重载方法,因此我写了一个新的构造函数:
private int integerArray[];
private float floatArray[];
/* constructor which creates the type of array based on the input of the second parameter */
public ArrayTools(int max, String arrayType) {
if (arrayType.equals("float")) {
floatArray = new float[max];
} else if (arrayType.equals("int")){
integerArray = new int[max];
}
现在的问题是我不知道如何以通用方式使用数组。我的方法仍然不知道创建了哪个数组,我不想用指定的参数调用它们。似乎没有意义。 构造函数不允许我在里面声明私有变量。否则我会这样做:
if (arrayType.equals("float")) {
private float genericArray = new float[max];
} else if (arrayType.equals("int")){
private int genericArray = new int[max];
}
【问题讨论】:
-
对于基元数组,恐怕除了复制粘贴之外没有其他解决方案。查看
java.util.Arrays类以获取类似的类。例如,针对每种类型的数组重新实现了 binarySearch 算法。
标签: java overloading