Skip to main content

Posts

Showing posts with the label java

Integer comparison using == gets tricky between -128 to 127.

Integer i=45;                                                                                                                                   Integer k=45;         System.out.println("i.hashcode= "+i.hashCode());         System.out.println("k.hashcode= "+k.hashCode());         System.out.println(i==k);         System.out.println(i.equals(k)); Out Put: i.hashcode= 45 k.hashcode= 45 true true Great, it seems work fine! now change the value of i=k=201.         Integer i=201;     ...

You have given an array in which numbers are first increasing and then decreasing. Find the maximum element in O(log n).

An integer array with unique elements has the following property – elements initially are in increasing order till a point after which they start to decrease. Implement a function to find the index of the maximum element in the array in less than linear time, i.e., O(n). Example: Input: array = {1, 3, 5, 7, 9, 8, 6, 4} Output: max index = 4 Max Index : 4.  Max Element value is : 9

Double check locking

Simple simulation of  muli-threading : few threads will read data from different sources and reduce them to get maximum from all the sources, An example of double check locking. lets make a  prototype of above problem. we will not go and solve it for generic case, we will simply create two thread thread1 and thread2;  this two threads will read data from two different sources and will will use a shared variable to get maximum of two data sets.  we will not go into details about what is singleton and double check locking, may be we see them in future post. in a sentence singleton is a design pattern that enable us to have only one     instantiation  of an object. that means we can't create  object of that class using new when and when ever we need to have object. So, our implementation logic goes as follows       1. start both the threads               find the max in each ...