簡體   English   中英

錯誤:類型不兼容:U無法轉換為int

[英]error: incompatible types: U cannot be converted to int

我有以下程序。

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是整數(但這僅是由於輸入測試用例),但這沒關系,為什么我的程序沒有編譯?

如果將列表項強制轉換為整數,為什么還要將中位數方法聲明為泛型?

將其更改為public static double median(List<Integer> l)並刪除所有強制轉換為int的類型。

您可以在Number元素上調用intValue()方法,而不是將其intValue()為int。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM