Метод contains для MyTreeSet
This commit is contained in:
@@ -49,4 +49,20 @@ public class MyTreeSet<E extends Comparable<E>> {
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean contains(E element) {
|
||||||
|
if (element == null) {
|
||||||
|
throw new NullPointerException("Нельзя добавить null в TreeSet!");
|
||||||
|
}
|
||||||
|
|
||||||
|
return contains(root, element);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean contains(Node node, E element) {
|
||||||
|
if (node == null) return false;
|
||||||
|
|
||||||
|
int cmp = element.compareTo(node.value);
|
||||||
|
if (cmp == 0) return true;
|
||||||
|
return cmp < 0 ? contains(node.left, element) : contains(node.right, element);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,4 +28,19 @@ class MyTreeSetTests {
|
|||||||
assertThrows(NullPointerException.class, () -> myTreeSet.add(null));
|
assertThrows(NullPointerException.class, () -> myTreeSet.add(null));
|
||||||
assertThrows(NullPointerException.class, () -> treeSet.add(null));
|
assertThrows(NullPointerException.class, () -> treeSet.add(null));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testContains() {
|
||||||
|
assertEquals(myTreeSet.contains(15), treeSet.contains(15));
|
||||||
|
treeSet.add(15);
|
||||||
|
myTreeSet.add(15);
|
||||||
|
assertEquals(myTreeSet.contains(15), treeSet.contains(15));
|
||||||
|
assertEquals(myTreeSet.contains(50), treeSet.contains(50));
|
||||||
|
treeSet.add(50);
|
||||||
|
myTreeSet.add(50);
|
||||||
|
assertEquals(myTreeSet.contains(50), treeSet.contains(50));
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class, () -> myTreeSet.contains(null));
|
||||||
|
assertThrows(NullPointerException.class, () -> treeSet.contains(null));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user