简体   繁体   English

如何在不同的List类中使用相同的内部类?

[英]How to use same inner class in different List classes?

I am working on a problem where I implement different Linked lists. 我正在解决一个实现不同链接列表的问题。 All the list classes include two inner classes; 所有列表类都包括两个内部类; a Node-class and an Iterator-class. 一个节点类和一个迭代器类。

These inner classes are entirely identical to each other. 这些内部类彼此完全相同。 In the Iterator-class, some of the methods rely on accessing information from the outer class, which works fine. 在Iterator类中,某些方法依赖于从外部类访问信息,这很好用。 Is there a way to do this in java, so that I would not need to include the very same code in all my different list-classes? 有没有办法在Java中做到这一点,这样我就不需要在所有不同的列表类中包含完全相同的代码? I feel clueless - I just don't know where to look. 我无能为力-我只是不知道在哪里看。

This is what my Node-class looks like: 这是我的Node类的样子:

class Node{
    Node next;
    Node previous;
    private T data;

    Node(T inn){
        data = inn;
    }

    public Node getNesteNode(){
        return next;
    }
    public T getData(){
        return data; 
    }
}

Edit: I realize the Node class is relying entirely on itself. 编辑:我意识到Node类完全依赖于自身。

Here is my simple Iterator: 这是我简单的Iterator:

class LenkeListeIterator implements Iterator<T>{
    private int field = 0;   
    Node denne = forste;

    @Override
    public boolean hasNext() {

        return field!= storrelse();
    }

    @Override
    public T next() {

        T data = denne.getData();
        denne = denne.getNesteNode();
        field++;
        return data;
    }
}

By definition, an inner class is an intrinsic part of the class containing it. 根据定义, 内部类是包含它的类的内在部分。 It can only be shared with subclasses, not peers or classes outside the hierarchy of the parent class entirely. 它只能与子类共享,而不能与父类的层次结构外部的同级或其他类完全共享。

There's nothing in your Node class that requires it to be an inner class, so you could just make it standalone. Node类中没有任何东西需要它成为内部类,因此您可以使其独立。 But if there were something that made it need to be an inner class, you could put all the parts that don't into a standalone class that is then subclassed in each of the parent classes to provide it with access to the parent's inner data. 但是,如果东西,使得它必须是一个内部类,你可以把所有成为一个独立的类,然后在每一个父类的子类,它提供访问父的内部数据部分。

Eg (roughly) : 例如(大致)

abstract class Example {
    protected int something;

    public void logic() {
        SomeType data = this.getParentData();
        /* ...do something with `data`... */
    }

    abstract protected SomeType getParentData();
}

Then an inner class in, say, Container would subclass it and provide getParentData . 然后,例如Container的内部类将其子类化并提供getParentData

class Container {
    private SomeType data;

    class ContainerExample extends Example {
        protected SomeType getParentData() {
            return data;
        }
    }
}

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

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