0

So I have been tinkering around with Java, and was wondering the difference in the following:

public void insert(Node<T> node) {
    //insertion code
}

vs 

public TreeNode<T> insert(Node node) {
   //insertion code
}

Assuming Node is a class declared:

public class Node<T> {
   //member variables
   //member functions 
}

Both methods compile and achieve the same goal. However, I was wondering if the first method eg. insert(Node<T> node) is simply more verbose and explicit than insert(Node node).

Doctor J
  • 27
  • 1
  • 7
  • The first empowers the compiler to check that you're only doing operations that are appropriate to a `Node`. The second basically switches off any kind of type checking on types that are used generically, so leaves you open to all kinds of problems. Don't do it! – Dawood ibn Kareem Jun 19 '18 at 22:19
  • It honestly depends on what your `insert` function wants to do with the node. For instance, if node has some variable of type `T`, then `insert` would be able to safely access that value's properties and methods, or alternatively, if as @DawoodibnKareem describes, you only want `insert` to accept nodes of type `T`. – otoomey Jun 19 '18 at 22:24

0 Answers0