Saturday, May 8, 2010

Seraching in Arrays in JAVA

We can search in a array for a value using the method binarySearch of Arrays class.
The search result will give correct output if the array is sorted.
If the array is not sorted the result is unpredictable.
Note: For predictable result array must be sorted before searching an element.

The following code explains this behavior:

Integer[] intArr={2,5,3,4,1};
for(Integer s: intArr)

System.out.print("Searching 5:"+Arrays.binarySearch(intArr,5)); // Will return -6 which is incorrect
System.out.print("Searching 2:"+Arrays.binarySearch(intArr,2)); // will return correct result 0, but not for every search

Arrays.sort(intArr); //Sorting the Array
for(Integer s: intArr)
System.out.println(System.lineSeparator()+Arrays.binarySearch(intArr,2)); // Always gives the correct result

equals method in JAVA

equals method of Object class and String class

Consider the below code

myClass obj1=new myClass();
myClass obj2=new myClass();

String str1=new String("AAAA");
String str2=new String("AAAA");



In both the cases two objects were created but for Strings the result is true and for myClass object the result is false.
The reason for this is
In object class the equals method compares the references and returns true if the references are point to the same object.
But in String class the equals method is overridden to check the values of the string object so it returns true.

About Me