Difficulties using iterator and generics in implementing binary search

I am learning Data Structures in java and I am having difficulty using generics in binary search trees.

For our purpose, we must implement a binary search tree using nodes that contain the parent, left and right node, as well as the data value.

The data value in our case takes the form of a Pair object. It looks like this:

public class Pair<A,B> {

    public final A fst;
    public final B snd;

    public Pair(A x, B y) {
        fst = x;  snd = y;
    }

    public String toString() {
      return new String("("+fst.toString()+", "+snd.toString()+")");
    }
}

A pair is associated with two different generics, with the first part being the key and the second being the value associated with this key.

I also need to implement Iterator in my BST class. I implement an Iterator in an inner class that looks something like this:

public Iterator<Pair<K,T>> iterator() {
    return new BSTMapIter<Pair<K,T>>(this.root, this.size, this.order);
}

private class BSTMapIter<Pair<K,T>> implements Iterator<Pair<K,T>> { <=== Compiler error "> expected"
    ...
    ... (Implementation here)
    ...
}

, , - "> expected", ( "<identifier expected>" ..). , <Pair<K,T>>, , . , , , , .

, , , , Pair - , , Iterator.

- , ? - , , , :)

+3
1

, BSTMapIter. K T. Pair . (, , .) , :

private class BSTMapIter<K,T> implements Iterator<Pair<K,T>>

, , BSTMapIter . , K T , , , :

private class BSTMapIter implements Iterator<Pair<K,T>>

:

// When it an inner class
public Iterator<Pair<K,T>> iterator() {
    return new BSTMapIter(this.root, this.size, this.order);
}

// When it a standalone generic class
public Iterator<Pair<K,T>> iterator() {
    return new BSTMapIter<K, T>(this.root, this.size, this.order);
}
+5

Source: https://habr.com/ru/post/1725590/


All Articles