【发布时间】:2020-11-12 02:42:36
【问题描述】:
我有这几个使用数组的方法,正如您所见,很多代码都是重复的,唯一真正的区别是每个方法的原始类型都发生了变化。我试图找出一种方法来保存这个重复的代码,但没有成功。
public class Stat {
// Private double array data
private double data[];
// Default constructor that creates a double array having a single element of 0.0
public Stat() {
data = new double[1];
data[0] = 0.0;
} // End of method
/*
* Constructs a Stat object of type double using the values held in d. The constructor
* then creates a double array of the same length as d and holds copies of the values of d. A
* reference to this new array is assigned to data.
*/
public Stat(double[] d) {
if (d == null) {
for (int c = 0; c < data.length; c++) {
data[c] = 0;
} // End of for loop
} // End of if condition
else {
data = new double[d.length];
for (int c = 0; c < data.length; c++) {
data[c] = d[c];
} // End of for loop
} // End of else statement
} // End of method
/*
* Constructs a Stat object of type float using the values held in f. The constructor
* then creates a double array of the same length as f and holds copies of the values of f. A
* reference to this new array is assigned to data.
*/
public Stat(float[] f) {
if (f == null) {
for (int c = 0; c < data.length; c++) {
data[c] = 0;
} // End of for loop
} // End of if condition
else {
float[] data = new float[f.length];
for (int c = 0; c < data.length; c++) {
data[c] = (float) f[c];
} // End of for loop
} // End of else condition
} // End of method
/*
* Constructs a Stat object of type int using the values held in c. The constructor
* then creates a double array of the same length as c and holds copies of the values of c. A
* reference to this new array is assigned to data.
*/
public Stat(int[] i) {
if (i == null) {
for (int c = 0; c < data.length; c++) {
data[c] = 0;
} // End of for loop
} // End of if condition
else {
int[] data = new int[i.length];
for (int c = 0; c < data.length; c++) {
data[c] = (int) i[c];
} // End of for loop
} // End of else condition
} // End of method
/*
* Constructs a Stat object of type long using the values held in lo. The constructor
* then creates a double array of the same length as lo and holds copies of the values of lo. A
* reference to this new array is assigned to data.
*/
public Stat(long[] lo) {
if (lo == null) {
for (int c = 0; c < data.length; c++) {
data[c] = 0;
} // End of for loop
} //End of if condition
else {
long[] data = new long[lo.length];
for (int c = 0; c < data.length; c++) {
data[c] = (long) lo[c];
} // End of for loop
} //End of else condition
} // End of method
【问题讨论】:
-
为什么要接受不同类型的数组?我的第一个倾向是只接受
double[]。如果用户有其他类型的数组,那么他们可以自己将其转换为double[],不需要这个类。 -
@JohnKugelman 这就像我的计算机科学课实验室的一个特定部分,我的教授出于某种原因希望这样做,我不知道为什么。如果这也有帮助,我可以在它之前发布代码
-
我同意,如果您只是要将元素转换为 double,则仅接受 double 更有意义。在任何情况下,您都可以使用 Arrays.fill(myArray, 0) 将数组填充为零,而不是执行 for 循环。
-
@dustinroepsch 所以没有方法可以减少冗余,因为这些方法接受不同的类型?
-
顺便说一下,原始数组被初始化为零(或假)
标签: java methods redundancy