public class Node<E> { int x; Node l, r; public Node() {} public Node(int x){ this.x = x; } public boolean search(int x){//Поиск элемента, если есть возвращает true if(this.x == x) return true; else if(this.x > x && l != null) return l.search(x); //Если x > or < значения в узле и если узел не пуст else if(this.x < x && r != null) return r.search(x); //Вызываем search от узла else return false; } } 

How to use generic correctly and how does the search function use the comparator to compare objects of non-primitive types?

    1 answer 1

    Here is my solution to your problem:

      public boolean treeSearch(Node<E> x, E k) { int cmp; while (x != null && k != x.value) { cmp = compare(x.value, k); if (cmp > 0) { x = x.left; } else { x = x.right; } } return x != null; } 

    Node is a type of a regular node, x is a node with which we start the search. k is the item we are looking for.

      private int compare(E val1, E val2) { return ((Comparable<? super E>) val1).compareTo(val2); } 

    Additional information ( an example of using the compare method with generalizations ) enter image description here

    E - here means in essence the type parameter, which during creation will be replaced with a real type, for example, as in the screenshot, during the creation of UseMyReal. In main, when we declare an instance of a class with the name myReal, we determine that the generic E will be replaced by the type Integer. Accordingly, in this implementation, the compare method will have to accept (Integer val1, Integer val2).

    • Do not tell me how to compare a variable of type E with zero? - Youlfey
    • for example, T x; compare (x, 0); Is it possible to do something like this? - Youlfey
    • Artem, I do not really understand what you want. I forgot to write that the compare method in this procedure will return only 1, 0, -1. ie if x.value <k, compare returns -1, if x.value> k compare returns 1, if it's equal to 0. Read the Schildt directory, there is a section about comparators, a lot of interesting things - diofloyk
    • In the form in which the method is now, it can compare (x.value, 0), but not (x.value, null) or (null, x) If you have more questions, ask - diofloyk
    • one
      If there are no additional questions, do not forget to mark the answers as correct. - diofloyk