java - comparable used as structure in a binary tree -
i have binary tree in java works nicely. want enhance data content in node. can add values on doing such as:
for( int = 1; <=10; i++ ) t.insert( new integer( ) );
which add item this:
public void insert( comparable item ) { current = parent = grand = header; nullnode.element = item; ... }
here format of tree:
private static class redblacknode { // constructors redblacknode( comparable theelement ) { this( theelement, null, null ); } redblacknode( comparable theelement, redblacknode lt, redblacknode rt ) { element = theelement; left = lt; right = rt; color = redblacktree.black; } comparable element; // data in node redblacknode left; // left child redblacknode right; // right child int color; // color }
for showing tree, that:
private void printtree( redblacknode t ) { if( t != nullnode ) { printtree( t.left ); system.out.println(t.element); printtree( t.right ); } }
while when programming in many other languages, element declared struct, sample code in java declared comparable, , taking 1 element integer. question is, how can use struct, in order able manipulate such doing in pseudo code:
system.out.println(t.element.valueint); system.out.println(t.element.firstnamestring); system.out.println(t.element.lastnamestring);
i have tried different syntax combinations based on previous posts, none has worked far.
for current code version added comments, check gist.
all suggestions appreciated.
comparable
interface. class can implement it. since thing tree needs know nodes how compare, , because comparable
provides precisely kind of knowledge, using comparable
sufficient tree.
however, may not enough you, because may want know other attributes part of comparable
implementation. reason may choose make redblacknode
class generic on exact type of item goes node, provided implements comparable
:
public class redblacktree <t extends comparable<? super t>> { private static class redblacknode { ... t element; } }
the rest of code remains same. methods of tree expose comparable
, such ones getting node information, use generic type t
instead.
you need supply type of node when creating redblacktree
, this:
redblacktree<myclass> tree = new redblacktree<myclass>();
of course, myclass
must implement comparable
. overall effect of change when code gets element tree, typed, letting access methods , fields without cast.
Comments
Post a Comment