简体   繁体   English

二进制搜索树,添加相同的元素异常。

[英]Binary Search Tree, adding the same element exception.

I want to add an element to a BinarySearchTree. 我想向BinarySearchTree添加一个元素。 I have a condition that checks if the element is already in the tree and if it is I want to throw an exception. 我有一个条件检查该元素是否已经在树中,如果它是我想抛出异常。 My problem is that I do not know what type, or what the name of this exception is. 我的问题是我不知道此异常的类型或名称。 I was looking for DublicateItemException but it does not work. 我一直在寻找DublicateItemException,但它不起作用。 I am working with java. 我正在使用Java。 Any ideas? 有任何想法吗? Thanks 谢谢

You can create your own exception for it. 您可以为其创建自己的异常。

Just create a new class DuplicateItemException , and make sure it extends Exception : 只需创建一个新类DuplicateItemException ,并确保它扩展了Exception

public static class DuplicateException extends Exception {

    private static final long serialVersionUID = 6188088059604835525L; //change the number, if needed - was auto generated by eclipse

}

If you want to use an existing class - maybe IllegalArgumentException might fit, though not perfectly. 如果要使用现有的类-也许IllegalArgumentException可能合适,尽管不是很完美。

The Java TreeSet simply returns false when you try to add an already-present element to the tree, but Queue sets an alternative precedent of throwing an IllegalStateException . 当您尝试向树中添加一个已经存在的元素时,Java TreeSet仅返回false ,但是Queue设置了引发IllegalStateException的替代先例。 There's no exception built into Java for the case you're looking for, though. 但是,对于您要寻找的情况,Java内置没有例外。

Why not create your own? 为什么不创建你自己的?

public class DuplicateItemException extends Exception
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM