-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 .

Turing85
  • 18,217
  • 7
  • 33
  • 58
Igor K
  • 67
  • 1
  • 5
  • 2
    What do you mean with `Optional<3>`? If you want to return an `Optional`, you need to return an `Optional`. Or do you just want the console output to change? In this case, just override [`public String toString()`](https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#toString-java.lang.Object-). – Turing85 Apr 26 '18 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. – Max Vollmer Apr 26 '18 at 21:49

2 Answers2

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);
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • From OP: "*It would be simpler return type `Optional` then I could write `return Optional.of(note.value)` and that's all, but I have to use `Optional`*" – Turing85 Apr 26 '18 at 21:49
  • 1
    This cannot be changed `public Optional getNodeHelper(Node note, Integer value)` but nothing is said about the caller : `getNode() `. – davidxxx Apr 26 '18 at 21:50
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();  
 } 
Aqeel Haider
  • 603
  • 7
  • 24