Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:重载特定类型的数组方法_Java_Overloading - Fatal编程技术网

Java:重载特定类型的数组方法

Java:重载特定类型的数组方法,java,overloading,Java,Overloading,我得到了这个ArrayTools类,它对整数数组执行许多数组操作 public class ArrayTools { private int arr[]; /* other variables */ public ArrayTools(int max) { arr = new int[max]; /* other stuff */ } 目前,该类的所有方法都使用该整数数组 现在我需要为浮点数组实现完全相同的方法。我显然不想将整个代码c&p到一个新的A

我得到了这个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];
    } 

使用Float和Integer对象,并使用泛型实现它

    public class ArrayTools<T>{
       private List<T> arr;
       public ArrayTools(int max) {
          arr = new ArrayList<T>(max);
             /* other stuff */
       }
    }
公共类数组工具{
私人名单;
公共阵列工具(int max){
arr=新阵列列表(最大值);
/*其他东西*/
}
}
要使用该类,您只需用这种方式即可

ArrayTools<Float> floatArrayTools = new ArrayTools<Float>(max);
ArrayTools<Integer> floatArrayTools = new ArrayTools<Integer>(max);
ArrayTools floatArrayTools=新的ArrayTools(最大值);
ArrayTools floatArrayTools=新的ArrayTools(最大值);

对于基元数组,恐怕除了复制粘贴之外,没有其他解决方案了。查看
java.util.Arrays
类中的类似类。例如,binarySearch算法将针对每种类型的数组重新实现。