【问题标题】:Overloading constructor of a class and each constructor will have different instance variables重载类的构造函数,每个构造函数会有不同的实例变量
【发布时间】:2020-10-19 21:41:38
【问题描述】:

我最初想创建一个“方法”Min,它将搜索一个数组的最小值并返回两个元素。一个代表最小值,另一个代表这个值的索引。为了做到这一点,我决定创建一个 Min 类和一个构造函数,将这两个元素存储为可通过 getter 和 setter 访问的实例变量(一个 double 和一个 int )。

棘手的部分是,然后,我想重载我的类,并添加第二个构造函数,这个构造函数将使用 2D 数组作为输入并有两个其他实例变量(一个 double[] 和一个 int[]) .

它正在工作,但是我很不舒服,因为我可以使用第一个构造函数创建此类的实例,并且仍然可以访问对这个构造函数没有意义的其他两个变量,反之亦然。

我可以为我的第二个构造函数创建一个完全不同的类来解决这个问题(例如:一个类 Min_array 和 Min_2Darray),但是我希望它们具有相同的名称,因为它代表相同类型的操作。

我相信应该有一种比我选择的更优雅的重载和检索多个结果的方法,我会很高兴得到一些建议或知道你的最佳实践是什么。谢谢。

我的第二个(更小的)担心是我必须在构造函数 2 中创建很多构造函数 1 的实例,这在内存分配方面似乎很奇怪并且根本没有效率。

我的班敏:

package operation;

public class Min {

    // ---------------- Instance Variables ------------------ 
    private int index = 0; 
    private double value = Double.POSITIVE_INFINITY; // important as i search for the MIN 
    private int[] ArrayIndex;   
    private double[] ArrayValue; 


    // ---------------- Constructor 01 ------------------ 
    public Min(double [] anArray) {
        for (int i = 0; i < anArray.length; i++) {
            if (anArray[i] < this.value) {
                this.value = anArray[i]; 
                this.index = i; 
            }
        }
    }

    // ---------------- Constructor 02 ------------------ 
    public Min(double [][] a2DArray, boolean accordingToRow) {

        int n_row = a2DArray.length; 
        int n_col = a2DArray[0].length; 

        if (accordingToRow == true) {
            this.ArrayIndex = new int [n_row]; 
            this.ArrayValue = new double [n_row];
            for (int i = 0; i < n_row; i++) {
                Min minofOneArray = new Min(a2DArray[i]);  // Here i call and create multiple instance of constructor 01.  
                this.ArrayIndex[i] = minofOneArray.getIndex(); 
                this.ArrayValue[i] = minofOneArray.getValue(); 
            }

        }else { // accordingToRow == false (so it according to Column now)
            
            this.ArrayIndex = new int [n_col]; 
            this.ArrayValue = new double [n_col]; 

            //need to loop to extract a column in this case
            double[] tmpArray = new double [n_row]; 

            for (int j = 0; j < n_col; j++) {
                for (int i = 0; i < n_row; i++) {
                    tmpArray[i] = a2DArray[i][j]; 
                }
                Min minofOneArray = new Min(tmpArray); 
                this.ArrayIndex[j] = minofOneArray.getIndex(); 
                this.ArrayValue[j] = minofOneArray.getValue(); 
            }

        }
        
    }

    // ---------------- Getters & Setters ------------------ 
    public int getIndex() {return this.index ; }
    public double getValue() {return this.value ; }

    public int[] getArrayIndex() {return this.ArrayIndex ; }
    public double[] getArrayValue() {return this.ArrayValue ; }

}

我班敏的测试:

package operation_test;

import java.util.Arrays;

import operation.Min;

class Test_MIN {
public static void main(String[] args) {
        
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> Test of the Min Class <<<<<<<<<<<<<<<<<<<<<<<<<<" );

        
        double [] anArray = { 0,  2 , 1 , -2 , 5 };  
        
        Min minOfArray = new Min(anArray); 
        
        System.out.println(minOfArray.getIndex());
        System.out.println(minOfArray.getValue());
        System.out.println("--------------- End of test 01 -----------------" );
        
        double [][] a2DArray = {{0.2,5,-1},{1,3,0.5}};  
        
        // 0  5 -1
        // 1  3 0.5
        
        
        Min minOf2DArray = new Min(a2DArray, true); // according to row 
       
        System.out.println(Arrays.toString(minOf2DArray.getArrayIndex()));
        System.out.println(Arrays.toString(minOf2DArray.getArrayValue()));
        System.out.println("--------------- End of test 02 -----------------" );
        
        Min minOf2DArray_AccordingToCol = new Min(a2DArray, false); // according to column
           
        System.out.println(Arrays.toString(minOf2DArray_AccordingToCol.getArrayIndex()));
        System.out.println(Arrays.toString(minOf2DArray_AccordingToCol.getArrayValue()));
        System.out.println("--------------- End of test 03 -----------------" );
        

    }
}

我班敏的成绩:

>>>>>>>>>>>>>>>>>>>>>>>> Test of the Min Class <<<<<<<<<<<<<<<<<<<<<<<<<<
3
-2.0
--------------- End of test 01 -----------------
[2, 2]
[-1.0, 0.5]
--------------- End of test 02 -----------------
[0, 1, 0]
[0.2, 3.0, -1.0]
--------------- End of test 03 -----------------

【问题讨论】:

  • 如果您希望不同的构造函数使用不同的实例变量集设置实例,那么您希望创建不同类的实例。那些可以继承具有公共部分的基类。该问题需要详细说明为什么这不是您可以接受的解决方案。
  • 当您总是可以只返回索引并稍后使用该索引访问元素时,为什么要返回具有索引和索引处的元素的对象?你可以做int min = arr[minIndex(arr)];
  • 谢谢你的回答,@Yunnosch,如果是这样,我要么必须创建两个不同的类,要么注意不要使用错误的 getter。 (我解决了这个问题,因为我正在考虑如果我想共享它,其他人如何使用我的代码,以及哪种方式使用和理解更“安全”?)。 @用户,它认为这是我来自Matlab的错误习惯,但是,确实在这种情况下它并没有像你提到的那样真正有用,但我仍然相信有选择的可能性可能是一个有趣的功能?
  • 您的评论只是因为我的评论而总结了您的见解(看起来就是这样)还是您希望我解释一下?如果您认为我的评论是一个答案(我害怕在没有帮助您的情况下仅表达显而易见的内容),我会将其变成官方答案,以形成完整的 Q/A 对。让我知道是否缺少任何内容以使其成为令人满意的答案。
  • @user 以防万一您没有注意到。在评论中 Op 试图 ping 你,但使用了不正确的 @ 语法。

标签: java constructor overloading min multipleoutputs


【解决方案1】:

如果您希望不同的构造函数使用不同的实例变量集设置实例,那么您希望创建不同类的实例。它们可以继承具有公共部分的基类。

(这虽然很短,但已被 OP 和 @user 视为答案。我创建它是为了将问题从未回答的问题列表中删除。让我知道当创建更有用或技术上更详细的答案时。我不介意删除我的。

【讨论】:

    【解决方案2】:

    我尝试了一些不同的东西,它更适合我表达的担忧:

    如果对某人有用,我会在此处发布代码。

    这个想法是使用一个类“元组”来检索多个输出,因此我不需要传递给构造函数。我仍然可以创建一个独特的类,将这两种方法作为静态方法。

    然而,我仍然不知道哪种方法是最好的,我想这取决于应用的方式。

    元组类:

    package utilitary;
    
    public class Tuple<T, U> {
        private final T first;
        private final U second;
    
        public Tuple(T first, U second) {
            this.first = first;
            this.second = second;
        }
    
        public T getFirst() {
            return this.first;
        }
    
        public U getSecond() {
            return this.second;
        }
    
        @Override
        public String toString() { 
            return this.first + " " + this.second;
        }
    }
    

    我的新班敏:

    package operation;
    
    import utilitary.Tuple;
    
    public class Min {
    
        // ---------------- Method 01 ------------------ 
        public static Tuple<Integer, Double> Min_Array(double [] anArray) {
            int index = 0; 
            double value = Double.POSITIVE_INFINITY; // important as i search for the MIN 
    
            for (int i = 0; i < anArray.length; i++) {
                if (anArray[i] < value) {
                    value = anArray[i]; 
                    index = i; 
                }
            }
            return new Tuple<>(index, value);
        }
    
        // ---------------- Method 02 ------------------ 
        public static Tuple<int[], double[]> Min_2DArray(double [][] a2DArray, boolean accordingToRow) {
    
            int[] arrayIndex; 
            double[] arrayValue; 
    
            int n_row = a2DArray.length; 
            int n_col = a2DArray[0].length; 
    
            if (accordingToRow == true) {
                arrayIndex = new int [n_row]; 
                arrayValue = new double [n_row];
                for (int i = 0; i < n_row; i++) {
    
                    Tuple<Integer, Double> minofOneArray = Min_Array(a2DArray[i]);  // Here i call method 01 multiple time 
                    arrayIndex[i] = minofOneArray.getFirst(); 
                    arrayValue[i] = minofOneArray.getSecond(); 
                }
    
            }else { // accordingToRow == false (so it according to Column now)
    
                arrayIndex = new int [n_col]; 
                arrayValue = new double [n_col]; 
    
                //need to loop to extract a column in this case
                double[] tmpArray = new double [n_row]; 
    
                for (int j = 0; j < n_col; j++) {
                    for (int i = 0; i < n_row; i++) {
                        tmpArray[i] = a2DArray[i][j]; 
                    }
    
                    Tuple<Integer, Double> minofOneArray = Min_Array(tmpArray);  
                    arrayIndex[j] = minofOneArray.getFirst(); 
                    arrayValue[j] = minofOneArray.getSecond(); 
                }
            }
            return new Tuple<>(arrayIndex, arrayValue); 
        }
    
    }
    

    测试:

    package operation_test;
    
    import java.util.Arrays;
    
    import operation.Min;
    import utilitary.Tuple;
    
    class Test_MIN {
    public static void main(String[] args) {
            
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> Test of the Min Class <<<<<<<<<<<<<<<<<<<<<<<<<<" );
    
            
            double [] anArray = { 0,  2 , 1 , -2 , 5 };  
            
            
            Tuple<Integer, Double> minOfArray = Min.Min_Array(anArray); 
    
            System.out.println(minOfArray.getFirst());
            System.out.println(minOfArray.getSecond());
            System.out.println("--------------- End of test 01 -----------------" );
            
            double [][] a2DArray = {{0.2,5,-1},{1,3,0.5}};  
            
            // 0.2  5 -1
            // 1  3 0.5
            
            Tuple<int[], double[]> minOf2DArray = Min.Min_2DArray(a2DArray, true); 
            
            System.out.println(Arrays.toString(minOf2DArray.getFirst()));
            System.out.println(Arrays.toString(minOf2DArray.getSecond()));
            System.out.println("--------------- End of test 02 -----------------" );
            
            
            Tuple<int[], double[]> minOf2DArray_AccordingToCol = Min.Min_2DArray(a2DArray, false); 
            
            System.out.println(Arrays.toString(minOf2DArray_AccordingToCol .getFirst()));
            System.out.println(Arrays.toString(minOf2DArray_AccordingToCol.getSecond()));
            System.out.println("--------------- End of test 03 -----------------" );
            
            
    
        }
    }
    

    结果

    >>>>>>>>>>>>>>>>>>>>>>>> Test of the Min Class <<<<<<<<<<<<<<<<<<<<<<<<<<
    3
    -2.0
    --------------- End of test 01 -----------------
    [2, 2]
    [-1.0, 0.5]
    --------------- End of test 02 -----------------
    [0, 1, 0]
    [0.2, 3.0, -1.0]
    --------------- End of test 03 -----------------
    

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 2014-01-12
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多