错误:不兼容的类型:U无法转换为int

时间:2017-02-08 12:26:01

标签: java generics

我有以下程序。

import java.util.*;

public class Solution {


    public static <U extends Number> double median(List<U> l) {

        double Q = 0;

        int n = l.size();
        if (n%2 == 0) {
            Q = ((int)l.get(n/2) + (int)l.get(n/2-1)) / (double)2;
        } else {
            Q = new Double((int)l.get(n/2));
        }

        return Q;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        List<Integer> l = new ArrayList<>();


        for (int i = 0; i < n; i++){
            l.add(sc.nextInt());
        }

        Collections.sort(l);

        double Q1 = 0, Q2 = 0, Q3 = 0;

        List<Integer> lower = new ArrayList<>();
        List<Integer> upper = new ArrayList<>();

        if (n%2 == 0) {
            lower.addAll(l.subList(0, n/2));
            upper.addAll(l.subList(n/2, n));
        } else {
            lower.addAll(l.subList(0, n/2));
            upper.addAll(l.subList(n/2 + 1, n));
        }

        Q2 = median(l);
        Q1 = median(lower);
        Q3 = median(upper);

        System.out.format("%.0f%n", Q1);
        System.out.format("%.0f%n", Q2);
        System.out.format("%.0f%n", Q3);

        sc.close();

    }
}

当我尝试从eclipse运行它时,它编译得很好并在我的本地机器上运行,但是当我将它提交给hackerrank时,我得到以下编译错误。

Solution.java:12: error: incompatible types: U cannot be converted to int
            Q = ((int)l.get(n/2) + (int)l.get(n/2-1)) / (double)2;
                           ^
  where U is a type-variable:
    U extends Number declared in method <U>median(List<U>)
Solution.java:12: error: incompatible types: U cannot be converted to int
            Q = ((int)l.get(n/2) + (int)l.get(n/2-1)) / (double)2;
                                             ^
  where U is a type-variable:
    U extends Number declared in method <U>median(List<U>)
Solution.java:14: error: incompatible types: U cannot be converted to int
            Q = new Double((int)l.get(n/2));
                                     ^
  where U is a type-variable:
    U extends Number declared in method <U>median(List<U>)
3 errors

我甚至不理解为什么我必须将每个列表元素强制转换为int,我认为因为U扩展了Number,所以我应该能够添加列表元素而不会返回int。有什么我不了解仿制药吗? Q1,Q2,Q3保证是整数(但这仅仅是因为输入测试用例),但这不重要,为什么我的程序编译不正确?

2 个答案:

答案 0 :(得分:0)

如果你将列表项强制转换为整数,为什么要将中值方法声明为泛型?

将其更改为docker run -itd -p 5432:5432 --name postgres_test -v /path/in/your/host :/path/in/your/container postgres_test psql -h 192.168.99.100 -p 5432 -U pguser -W pgdb 并将所有转换删除为int。

答案 1 :(得分:0)

您可以在intValue()元素上调用Number方法,而不是将它们转换为int。

https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html#intValue--