Java – determines the type of object

If I have this situation:

interface Node {}

class EmptyNode implements Node {}

class NotEmptyNode implements Node {}

Now I have another class,

class List {
  Node n;
}

What I'm trying to do is find a way to determine the size of the node list I already have logic:

public int getSize(Node start) {
    if (start==EmptyNode) {  //Can't do this,not sure how to check if its an empty Node
        return 0;
    }
    else {
        return 1 + getSize(start.next()); //Want to add 1 and move to next Node
    }
}

Since both emptynode and notemptynode are node types, I know I need to implement a function that I can write in the interface. This function will be implemented in two classes and can calculate when the end of the list is hit

Solution

You handle instances here This means that you can put an isempty () method in the node interface and use it to check whether the node is empty

interface Node {
    boolean isEmpty();
}

class EmptyNode implments Node {
    @Override
    public boolean isEmpty() { return true; }
}

class NotEmptyNode implements Node {
    @Override
    public boolean isEmpty() { return false; }
}

...

public int getSize(Node start) {
    if (start.isEmpty()) {
        ...
    }
    else {
        ...
    }
}

Another solution is to let node implement a size() function:

interface Node {
    int size();
    Node next();
}

class EmptyNode implements Node {
    @Overide
    public int size() {
        return 0;
    }
    ...
}

class NotEmptyNode implements Node {
    @Overide
    public int size() {
        return 1 + next().size();
    }
    ...
}

...

class List {
    Node n;

    public int getSize() {
        return n.size();
    }
}

Which gets rid of the if statement altogother

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>