Posts

Showing posts from January, 2016

Override equals and hashcode in Java

It is not always necessary to override hashcode and equals. But if you think you need to override one, then you need to override both of them. Let's analyze what whould happen if we override one but not the other and we attempt to use a  Map . Say we have a class like this and that two objects of  MyClass  are equal if their  importantField is equal (with  hashCode  and  equals  generated by eclipse) public class MyClass { private final String importantField ; private final String anotherField ; public MyClass ( final String equalField , final String anotherField ) { this . importantField = equalField ; this . anotherField = anotherField ; } public String getEqualField () { return importantField ; } public String getAnotherField () { return anotherField ; } @Override public int hashCode () { final int prime = 31 ...

Binary search tree operations - Java

Binary Search Tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. There must be no duplicate nodes. The above properties of Binary Search Tree provide an ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no ordering, then we may have to compare every key to search a given key. Searching a key To search a given key in Bianry Search Tree, we first compare it with root, if the key is present at root, we return root. If key is greater than root’s key, we recur for right subtree of root node. Otherwise we recur for left subtree. // A utility function to search a given key in BST public Node search(Node root, int key) {     // Base Cases: ro...