小编Jua*_*pes的帖子

为什么javac认为在泛型类上使用泛型返回调用方法是不安全的?

请考虑以下代码:

public class Main {
    public static class NormalClass {
        public Class<Integer> method() {
            return Integer.class;
        }
    }

    public static class GenericClass<T> {
        public Class<Integer> method() {
            return Integer.class;
        }
    }

    public static void main(String... args) {
        NormalClass safeInstance = new NormalClass();
        Class<Integer> safeValue = safeInstance.method();

        GenericClass unsafeInstance = new GenericClass();
        Class<Integer> unsafeValue = unsafeInstance.method();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我编译它:

$ javac -Xlint:unchecked Main.java 
Run Code Online (Sandbox Code Playgroud)

它返回:

Main.java:16: warning: [unchecked] unchecked conversion
        Class<Integer> unsafeValue = unsafeInstance.method();
                                                          ^
  required: Class<Integer>
  found:    Class
1 warning
Run Code Online (Sandbox Code Playgroud)

请注意,即使返回类型没有引用泛型类型,也只会将通用方法视为不安全. …

java generics javac raw-types

16
推荐指数
1
解决办法
723
查看次数

如何在JavaScript中实现二进制搜索

https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/p/challenge-binary-search

我正在遵循伪代码在链接上实现算法,但不知道我的代码有什么问题.

这是我的代码:

/* Returns either the index of the location in the array,
  or -1 if the array did not contain the targetValue */

    var doSearch = function(array, targetValue) {
    var min = 0;
    var max = array.length - 1;
    var guess;

    while(min < max) {
        guess = (max + min) / 2;

        if (array[guess] === targetValue) {
            return guess;
        }
        else if (array[guess] < targetValue) {
            min = guess + 1;
        }
        else {
            max = guess - …
Run Code Online (Sandbox Code Playgroud)

javascript algorithm binary-search bisection

2
推荐指数
1
解决办法
5604
查看次数

给出一个测试案例,其中“算法简介”中的堆排序失败

我正在阅读《算法入门》中的heapsort,那里说(1)以自底向上的方式构建最大堆。(2)然后与最后一个元素交换,并在第一个元素上调用max hepify,并继续这样。

让我们以这个输入为例-

->7 10 20 3 4 49 50
Run Code Online (Sandbox Code Playgroud)

建立最大堆的步骤将是

7 10 50 3 4 49 20
7 10 50 3 4 49 20
50 10 7 3 4 49 20
Run Code Online (Sandbox Code Playgroud)

这是最大的堆建立。现在我们与最后交换

20 10 7 3 4 49 | 50
Run Code Online (Sandbox Code Playgroud)

现在我们在20上调用max heapify,什么也没有发生n我们将20放在n-1位置是错误的。

我们以自下而上的方式创建堆,但是以自上而下的方式调用heapify,我认为这就是为什么在此输入中给出错误的原因。

sorting algorithm heapsort

0
推荐指数
1
解决办法
1016
查看次数