java - Exception being thrown incorrectly -
i using pre-written classes textbook , implementing them program. duplicate error being thrown every time try add new element tree, , have no idea why, , haven't manipulated written code @ all.
basically, program prompts user enter information, , take info , add student binary search tree, have following textbook:
abstractbinarytree class:
public abstract class abstractbinarysearchtree<e extends comparable<? super e>> implements binarysearchtree<e> public void add( e element ) { if ( element == null ) { throw new searchtreeexception(); } setroot( add( null, this.root(), element ) ); size++; } ...
linkedbst class:
public class linkedbst<e extends comparable<? super e>> extends abstractbinarysearchtree<e> { public linkedbst( e element ) { if ( element == null ) { throw new java.lang.illegalargumentexception( "null element illegal" ); } this.root = new bstnode<e> ( element ); this.size = 1; } protected void setroot( bstnode<e> newroot ) { this.root = newroot; } protected bstnode<e> add( bstnode<e> parent, bstnode<e> node, e element ) { if ( node == null ) { // base case node = new bstnode<e> ( element ); node.parent = parent; } else { // recursive case int compareresult = element.compareto( node.element ); if ( compareresult < 0 ) { // recursive case - left node.leftchild = add( node, node.leftchild, element ); } else if ( compareresult > 0 ) { // recursive case - right node.rightchild = add( node, node.rightchild, element ); } else { throw new searchtreeexception( "duplicate element: " + element.tostring() ); } } return node; } ...
as binarysearchtree
interface, , i'm calling method seperate class:
... abstractbinarysearchtree<student> tree = new linkedbst<student>(); //this problem? ... tree.add(new student(studentnumber, firstname, lastname, major, gpa));
so, know partially works @ least. i'm able add @ least 1 record tree, when try add second 1 regardless of information, keeps throwing searchtreeexception
a(also pre written) , won't add others. still new abstract classes binary search trees doing best @ implementing this, if can see going wrong awesome!
if @ comparable
interface , compareto(..)
method, states
returns negative integer, zero, or positive integer object less than, equal to, or greater specified object.
if you're seeing searchtreeexception
, means piece of code
int compareresult = element.compareto( node.element ); if ( compareresult < 0 ) { // recursive case - left node.leftchild = add( node, node.leftchild, element ); } else if ( compareresult > 0 ) { // recursive case - right node.rightchild = add( node, node.rightchild, element ); } else { throw new searchtreeexception( "duplicate element: " + element.tostring() ); }
used implementation of compareto(..)
returned 0
.
from comments, stated using default (ide-)created implementation of method returns 0
. need fix compareto
method works documented in javadoc.
Comments
Post a Comment