Java - generic types -


i trying create binary tree using generic typing , have error not understand. tried 2 ways of coding , second worked. not understand why first failing.

i have following common code:

public class mytreea <t extends comparable<t>>  {         class bt_node<t extends comparable<t>>            {             t           value;             bt_node<t>  left;             bt_node<t>  right;              bt_node(t node_value)                    {                      this.value   = node_value ;                     left         = null;                     right        = null;                   }            }            

the difference in insert procedure: works:

 private bt_node<t> insert(bt_node<t> node, bt_node<t> newnode) {       if ((node.value).compareto(newnode.value) == 0) { . . . } 

but fails

  private bt_node insert(bt_node node, t value) {         if (value.compareto(node.value) == 0) { . .   

with:

mytreea.java:28: error: method compareto in interface comparable<t#2> cannot applied given types;             if (value.compareto(node.value) == 0) required: t#1 found: comparable reason: actual argument comparable cannot converted t#1 method invocation conversion t#1,t#2 type-variables: t#1 extends comparable<t#1> declared in class mytreea t#2 extends object declared in interface comparable 

obviously if call bt_insert 2 nodes parameters tis fine. (and code cater creating function) have preferred not way.

thanks

you should able use second example following signature:

private bt_node<t> insert(bt_node<t> node, t value)  

the example gave uses "raw types" (i.e. generic class without generic parameter), bad idea , arguably exists backwards compatibility java 1.4. bt_node generic class, should always give generic parameter.

in case didn't, equivalent passing in bt_node<?>, in node have had value generic parameter. compiler not guarantee value passing in of correct type - first argument bt_node<int> example, while t string.

by passing in generic parameter t, compiler can check type of value , type of node do match.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -