简体   繁体   English

仅适用于 Integer 的通用 Java 类的方法

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

I have a generic class like the Java Linked List with a method sum() which should only be accessible if the list is of type Integer.我有一个像 Java Linked List 这样的通用类,它有一个方法 sum() ,只有当列表是 Integer 类型时才应该可以访问它。 The constructor and sum() method look like this:构造函数和 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;
    }

...

Before executing the method I dont want to ask whether the sentinel is instace of Integer.在执行该方法之前,我不想询问哨兵是否是 Integer 的实例。 I was wondering if there was a way to not show sum() at all if the list is of type String我想知道如果列表是 String 类型,是否有办法完全不显示 sum()

I tried changing JList to an abstract class and implementing a seperate class for Integers like this:我尝试将 JList 更改为抽象类并为 Integers 实现一个单独的类,如下所示:

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

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

and

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;
    }
}

But when trying to create a list但是在尝试创建列表时

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

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

it says "Cannot instantiate the type JList"它说“无法实例化 JList 类型”

Your inheritance attempt is correct.您的继承尝试是正确的。 Just don't make the base class abstract , so that you can instantiate it.只是不要让基类abstract ,这样你就可以实例化它。

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

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

Note that the sum method should only be defined for the JListInteger sub class, since the base class doesn't necessarily support sum operation.请注意,只能为JListInteger子类定义sum方法,因为基类不一定支持sum运算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM