简体   繁体   中英

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. 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? I feel clueless - I just don't know where to look.

This is what my Node-class looks like:

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.

Here is my simple 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. 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 .

class Container {
    private SomeType data;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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