-1

It is the part of Main method

    System.out.println(node.getNode(3)); //in the end i have to get Optional[3]
    System.out.println(node.getNode(7)); // in the end I have to get Optional[7]

And I have the methods

public Optional<Node> getNode(Integer value) {
    return getNodeHelper(this, value);
}

public Optional<Node> getNodeHelper(Node note, Integer value) {
    if (note.value.equals(value)) {
        return Optional.of(note);
    } else if (note.value < value) {
        return getNodeHelper(note.right, value);
    } else if (note.value < value) {
        return getNodeHelper(note.left, value);
    }
    return Optional.empty();
}

The questions is next, how I should to do return, that in the end to get Optional[3] or Optional[7] not some Optional[ee.ttu.iti0202.tree.Node@6615435c]

This line I cannot change (The task from University)

public Optional<Node> getNodeHelper(Node note, Integer value)

Variable that i use in this class are:

private Integer value;
Node left;
Node right;

It would be simpler return type Optional<Integer> then I could write return Optional.of(note.value) and that is all, but I have to use Optional<Node>.

The lecturer advised to use override, but i have not understood how to do it .

2
  • 2
    What do you mean with Optional<3>? If you want to return an Optional<Integer>, you need to return an Optional<Integer>. Or do you just want the console output to change? In this case, just override public String toString(). Commented Apr 26, 2018 at 21:46
  • You seem to be having a XY problem. You are basically asking how to return an Optional holding the value that you give the method. That makes no sense. Please try to rephrase your question with a problem, not with the solution you believe you need. Commented Apr 26, 2018 at 21:49

2 Answers 2

1

In the getNode() method map the returned Optional<Node> to Optional<Integer> :

public Optional<Integer> getNode(Integer value) {
    return getNodeHelper(this, value).map(Node::getValue);
}
Sign up to request clarification or add additional context in comments.

2 Comments

From OP: "It would be simpler return type Optional<Integer> then I could write return Optional.of(note.value) and that's all, but I have to use Optional<Node>"
This cannot be changed public Optional<Node> getNodeHelper(Node note, Integer value) but nothing is said about the caller : getNode() .
0

In the Node class can you write toString() Method?? and return the value of Integer in it ?

If you write the toString() method then it will not return Optional[ee.ttu.iti0202.tree.Node@6615435c] value instead it will return what you return in the toString() method.

//overriding the toString() method 
public String toString(){ 
  return value.toString();  
 } 

1 Comment

Thanks a lot!! exactly what I need

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.