【问题标题】:Do I have to create integers for a counter that calls a method?我是否必须为调用方法的计数器创建整数?
【发布时间】:2014-06-18 16:13:34
【问题描述】:

问题是:

Complete the method occursMoreTimes based on the requirements in its comment. 
/** 
*Returns true if the number of times val1 occurs in the array is strictly greater 
*than the number of times val2 occurs in the array. Otherwise, return false. 
*If you wish, you can call the findNumberOf method you wrote above. 
**/ 

我的回答是这样的:

public boolean occursMoreTimes(int[] arr, int val1, int val2){
    if(findNumberOf(arr, val1) > findNumberOf(arr, val2)){
        return true
    }
    else {return false;
    }
}

但是答案键为我在 if 语句中编写的方法调用声明了一个 int,如下所示:

public boolean occursMoreTimes(int[] arr, int val1, int val2){
    int countVal1 = findNumberOf(arr, val1);
    int countVal2 = findNumberOf(arr, val2);
        if(countVal1 > countVal2){
            return true
        }
        else {return false;
        }
}

我的回答可以吗?将方法调用声明为 int 是否有优势?

【问题讨论】:

    标签: java arrays methods int


    【解决方案1】:

    两者是等价的。在您的第一个示例中,编译器代表您创建了两个临时整数。

    【讨论】:

      【解决方案2】:

      declaring a method call as an int 这个短语并不完全正确。

      解决方案所做的只是声明一个 int 类型的常规变量以存储方法 findNumberOf() 的返回值。

      在您的示例中,为findNumberOf()s 返回值声明单独的 int 确实没有任何优势。

      可能有优势的场景是:

      1. 您需要在整个函数中多次引用这些值。因此,您可以节省对同一方法的多次调用以及代码空间(名称很可能比对方法的调用短)。

      2. 您可以为返回值指定一个特定的名称,从而提高代码的可读性。

      这一切都取决于情况。在你的情况下,这没有什么区别。

      【讨论】:

        猜你喜欢
        • 2011-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        • 1970-01-01
        • 2019-01-02
        相关资源
        最近更新 更多