T
T
Tarasov Konstantin2015-04-19 20:39:45
Java
Tarasov Konstantin, 2015-04-19 20:39:45

How to properly organize type casting when working with a generic stack?

I am making a parser and I have this situation:
There is a single Node superclass for all nodes of the parse tree.
The parser in the course of its work uses the stack, the type of values ​​\u200b\u200bwhich are stored in it, of course Node.
Attention to the question, at what stage is it better to cast types? Because if we have, for example, such a node:

class AssignNode extends Node {
    private VarNode left;
    private ExpressionNode right;
    //Конструктор и геттеры сеттеры

At what stage is it better to cast types? Immediately after getting from the stack, before passing to the constructor, or make the constructor parameters of type Node and cast the types already inside it?
Z.Y. There was also an unhealthy idea to make the pop () method parameterized and cast types inside it, well, like
private <T extends Node> T pop() {
    Node element = ...
    if (element instanceof T) return (T) element;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bromzh, 2015-04-21
@bromzh

At runtime, your parameterized type is replaced by Object. The last code will be simply meaningless. Also instanceof .
Type lead at the time of receipt:
MyClass a = (MyClass) stack.pop();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question