簡體   English   中英

僅適用於 Integer 的通用 Java 類的方法

[英]Method of generic Java class that only works for Integer

我有一個像 Java Linked List 這樣的通用類,它有一個方法 sum() ,只有當列表是 Integer 類型時才應該可以訪問它。 構造函數和 sum() 方法如下所示:

public class JList<T> {
    public JNode<T> sentinel;

    public JList() {
        this.sentinel = new JNode<T>();
    }

    // Sum of every entry
    public int sum() {
        JNode<Integer> n = (JNode<Integer>) this.sentinel.next;
        int sum = 0;

        while (n != null) {
            sum += n.element;
            n = n.next;
        }
        return sum;
    }

...

在執行該方法之前,我不想詢問哨兵是否是 Integer 的實例。 我想知道如果列表是 String 類型,是否有辦法完全不顯示 sum()

我嘗試將 JList 更改為抽象類並為 Integers 實現一個單獨的類,如下所示:

public abstract class JList<T> {
    public JNode<T> sentinel;

    public JList() {
        this.sentinel = new JNode<T>();
    }
    
    public abstract int sum();

public class JListInteger extends JList<Integer> {

    public int sum() {
        JNode<Integer> n = (JNode<Integer>) this.sentinel.next;
        int sum = 0;

        while (n != null) {
            sum += n.element;
            n = n.next;
        }
        return sum;
    }
}

但是在嘗試創建列表時

public class Test {
    public static void main(String[] args) {

        JList<String> l1 = new JList<>();
    }
}

它說“無法實例化 JList 類型”

您的繼承嘗試是正確的。 只是不要讓基類abstract ,這樣你就可以實例化它。

public class JList<T> {
    public JNode<T> sentinel;

    public JList() {
        this.sentinel = new JNode<T>();
    }
}

請注意,只能為JListInteger子類定義sum方法,因為基類不一定支持sum運算。

暫無
暫無

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

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